Fmod does not work as expected(c programming) [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
(the problem is caused by me and has been solved ,greetings from the newbie)I apologize to everyone, my function type was integer i just realized it, I opened it because I worked for hours, I have to delete it).
I am using gcc 9.3.0 version and standard settings. In the code in the example, I am getting 7 while waiting to get output 7.14. What could be the reason for this?(im using gcc main.c -lm -o main when compiling,what I'm trying to do is print as an integer if the double number is equal to integer, otherwise print it as a double,sorry for the adjustments, this is the last and proper version)
#include <stdio.h>
#include <math.h>
int try(double a);
int main() {
double b = 7.14;
double x;
double temp;
x = try(b);
if (fmod(x, 1) == 0.0) { // print 7 in this function
temp = x;
printf("%d", (int)temp);
}
else if (fmod(x, 1) != 0.0) {
printf("%f", x);
}
return 0;
}
int try(double a) {
if (fmod(a, 1) != 0.0) {
printf("%lf", a); // print 7.14 in this function
} else if (fmod(a, 1) == 0.0) {
printf("%d", (int)a);
}
return a + 0;
}

With gcc version 10.2.0 (GCC)
Got the result 7.140000
Some code-format and debug output.
#include <math.h>
#include <stdio.h>
double func_try(double a) { return a + 0; }
int main() {
double b = 7.14;
double x;
x = func_try(b);
printf("%lf\n", fmod(x, 1));
if (fmod(x, 1) != 0.0) {
printf("%lf", x);
} else if (fmod(x, 1) == 0.0) {
printf("%d", (int)x);
}
return 0;
}
$gcc main.c -lm -o main
$./main
0.140000
7.140000

fmod(7.14, 1) = 0.14, thus it hit the first if and print 7.14.
Compute remainder of division
Returns the floating-point remainder of numer/denom (rounded towards zero):
fmod = numer - tquot * denom
Where tquot is the truncated (i.e., rounded towards zero) result of: numer/denom.
http://www.cplusplus.com/reference/cmath/fmod/

Related

Wrote a program to get the binary output of a decimal, and the result is inverted [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
Below is the program for my assignment. All of it was given except the printing and logic. I searched many videos about it and did what they did, but 15's binary is 1111 and the result was 0000
#include <stdio.h>
#include <math.h>
// Function to convert decimal to binary
// The function is void type so, print the result inside the function
void decimal2Binary(int dec) {
// array to store binary number
int binaryNumber[32];
// Your logic goes here
// fill out the binaryNumber
// i to increment the loop and terminate
int i = 0;
// We are interested in positive numbers for now
while (dec > 0) {
// Please add your logic to build the binary array
binaryNumber[i] = dec%2;
dec = dec/2;
i++;
}
// Print the binary array.
printf("Binary: ");
for (int j = i - 1; j >= 0; j--) {
printf("%d",binaryNumber[i]);
}
}
// The main function goes here
// The main function calls the decimal2Binary
int main() {
int decimal = 15;
printf("Decimal: %d equal to ", decimal);
decimal2Binary(decimal);
return 0;
}
DECIMAL TO BINARY (RECURSIVE):
#include <stdio.h>
int find(int dec_num)
{
if (dec_num == 0)
return 0;
else
return (dec_num % 2 + 10 *
find(dec_num / 2));
}
int main()
{
int decimal_number;
scanf("%d", &decimal_number);
printf("%d", find(decimal_number));
return 0;
}
DECIMAL TO BINARY (ITERATIVE):
#include <stdio.h>
long dec_to_bin(int decimalnum){
int binarynum = 0;
int mod, place = 1;
while(decimalnum != 0){
mod = decimalnum % 2;
decimalnum = decimalnum/2;
binarynum = binarynum + (mod*place);
place = place*10;
}
return binarynum;
}
int main() {
int decimalnum;
scanf("%d", &decimalnum);
printf("enter a decimal number:\n %ld", dec_to_bin(decimalnum));
return 0;
}

Primality Test Comparison [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I found a new primality test below which determines if 1000000007 is prime.
How does its speed compare to other existing primality algorithms?
Does it win the award for most "computationally worthless" primality test?
Thanks.
EDIT
Was able to improve speed using this method described here:
https://math.stackexchange.com/questions/3979118/speedup-primality-test
"So it's enough to go from x=n/2 up to n/2+√n/2. With this improvement, your algorithm will still be somewhat slower than your isPrimeNumber routine--just because calculating a gcd is slower than calculating divisibility. This will be feasible for testing numbers with maybe 15-20 digits, but you would need completely different methods to test something much larger, like the 183-digit number you mention."
// Primality Test
// Every n is prime if all lattice points on x+y=n are visible from the origin.
#include <stdio.h>
#include <stdint.h>
#include <math.h>
uint64_t gcd(uint64_t a, uint64_t b)
{
return (b != 0) ? gcd(b, a % b) : a;
}
int isPrimeNumber(uint64_t n)
{
if (n == 1) return 0;
if (n == 2 || n == 3) return 1;
if (n % 2 == 0) return 0;
// Start near line x=y.
uint64_t x = (n / 2) + 2;
uint64_t y = n - x;
uint64_t count = sqrt(n) / 2;
for (uint64_t i = 0; i < count; ++i) {
// Check lattice point visibility...
if (gcd(x, y) != 1) return 0;
x++; y--;
}
return 1;
}
int main(int argc, char* argv)
{
uint64_t n = 1000000007;
if (isPrimeNumber(n) == 1)
{
printf("%llu prime.", n);
}
else
{
printf("%llu not prime.", n);
}
return 0;
}
When you write any code, you should do basic debugging to verify that your code does what you think it does. Run your code on a few small numbers; print values of x and y to verify that it does the correct checks.
In addition to this, if you mix integers and floating-point variables, you should be careful: implicit conversions e.g. from float to unsigned can lead to data loss and completely incorrect calculations. Compilers usually warn about this; you should compile with all warnings enabled -Wall and pay attention to what the compiler says.
It looks like you should always have x + y = n during your computations - this is your invariant. This can be more easily expressed like this:
// initialization
x = n / 2;
y = n - x;
// it should be evident that your invariant holds here
do {
...
x++; y--;
// your invariant holds here too, by induction
}

Understanding this output from a factorial recursion [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
In this factorial recursion "printf" outputs 2 6 8, Can't understand why...
#include <stdio.h>
int f(int n)
{
int k;
if (n==1)
return 1;
else
k = n*f(n-1);
printf("%d ",k);
}
int main()
{
f(4);
}
The original version of the code in the question was:
int f(int n) {
int k;
if (n == 1)
return 1;
else
k = n * f(n - 1);
printf("%d ", k);
}
int main() {
f(4);
}
This code has undefined behavior because you do not return a value properly if n != 1, causing the calling code to use an unpredictable value in its own calculation. The behavior is undefined, anything can happen.
Adding the return statement fixes this issue. Note however these extra points:
variable k is useless in the f function.
f should return 1 for an argument of 0.
you should output a newline after the number and return 0 in main.
Here is modified version:
#include <stdio.h>
int f(int n) {
if (n <= 1)
return 1;
else
return n * f(n - 1);
}
int main() {
int i;
for (i = 0; i < 10; i++) {
printf("%d! = %d\n", i, f(i));
}
return 0;
}
There are many mistakes you are making here:
printf("%d ",k);
this line is never going to be executed because in any case if() else clause will return before it.

C Function: Count the occurrences of a digit in an integer [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm receiving Output: 1. I should count the number of times a digit appear in an integer, for example, for number 1222345 and n = 2 Should appear 3 times.
int countOccurrences(int n, int num)
{
int i,k;
i=0;
while(num!=0)
{
k=num%10;
num=num/10;
if(k==n)
{
i++;
}
}
}
// Main
void main()
{
int num= 1222345;
int n = 2;
printf("Occurance of a number: %d", countOccurrences(n,num));
}
You have undefined behavior in the code. The function is supposed to return an int and it didn't.
Solution is to add return i in the end of other function. This will give you correct result. In the countOccurrences() function
...
if(k==n)
{
i++;
}
}
return i;
}
I was skipping the discussion of error check and all that. As chux mentioned for n<=0 case you might want to add a different way of handling it but you didn't add it. Atleast consider those case and put an error message on whatever input you need.
Some corner cases are
n=0,m=0.
Negative value of n or m.
Put a return on your countOccurrences function please
int countOccurrences (int n, int num) {
int i, k;
i = 0;
while (num! = 0)
{
k = num% 10;
num = num / 10;
if (k == n)
{
i ++;
}
}
return i; }
As other have pointed out, there are important issues with your code.
Here is a recursive solution that you may find interesting:
int countOccurrences(int n, int num)
{
int count = ((num % 10) == n);
return (num < 10) ? count : count + countOccurrences(n, num / 10);
}
Few general remarks about your code:
When using printf(), you should #include <stdio.h>.
main() should return int.
Place spaces around operators and format your code consistently. This k = num % 10; is more readable than k=num%10;. (There's more to code formatting than a matter of taste; without spaces you create areas full of characters which are more difficult to parse for our visual system.)

gcc seems to compile my code wrong? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am rather new in C and i was trying to solve some exercises in my textbook and encountered a wierd Problem. although my Task is undeniably easy the program just wont work right. after some Trials it seems that the fault is on the Compiler but as much as this sounds unreasonable its the only justification i can bring up
without any further delay here is the code
#include <stdio.h>
double power(double n, int p);
int main(void)
{
double x, xpow;
int exp;
printf("Enter a number and the positive integer power");
printf(" to which\nthe number will be raised. Enter q");
printf(" to quit.\n");
while (scanf("%lf%d", &x, &exp) == 2)
{
xpow = power(x,exp);
printf("%.3g to the power %d is %.5g\n", x, exp, xpow);
printf("Enter next pair of numbers or q to quit.\n");
}
printf("Hope you enjoyed this power trip -- bye!\n");
return 0;
}
double power(double n, int p)
{
double pow = 1;
int i ;
if ( n == 0 && p == 0)
{
printf("0 to zeroth power is undefined\nwe will use therefor 1 instead\n");
p = 1 ;
}
if (p >= 0)
{
for (i = 1 ; i <= p ; i++);
pow *= n ;
}
else
{
for (i = -1 ; i >= p ; i--);
pow *= 1/n ;
}
return pow;
}
the programs intent is clear the problem is when I input some test cases the output is wrong
like
(5 2)
the output should be 25 but I get 5
(5 6)
the output should be 15625 but i get 5
after examining this problem with gdb I found that instead of initializing i to 1 it is initialized to 3 for no obvious reason and with the second input i is initialized to 7
i want to know why
I'm using gcc.
Why do you blame the compiler, I would blame my eyes first you have an extra semicolon in both your for loops
for (i = 1 ; i <= p ; i++);
change it to
for (i = 1 ; i <= p ; i++)

Resources