Home > front end >  Using remainder in C with two positive doubles turns it to negative?
Using remainder in C with two positive doubles turns it to negative?

Time:09-25

I am just starting to learn C programming but whenever I run this:

double a = 9.92; 
double b = 2.00;
printf("%.2lf,  %.2lf,  %.2lf", a, b, remainder(a, b));

The output is always $-0.18. The output that I was hoping for is $1.92.

CodePudding user response:

The remainder function rounds the result of the division to the nearest integer, which means you can get a negative result. From the man page:

The remainder() function computes the remainder of dividing x by y. The return value is x-n*y, where n is the value x / y, rounded to the nearest integer. If the absolute value of x-n*y is 0.5, n is chosen to be even.

So given your input, 9.92 / 2 results in 4.96 which rounded to the nearest integer is 5. Then you have 9.92 - (5 * 2.00) == 9.92 - 10.0 == -0.08.

You want to instead use fmod, which rounds the division toward 0. The man page for that states:

The fmod() function computes the floating-point remainder of dividing x by y. The return value is x - n * y, where n is the quotient of x / y, rounded toward zero to an integer.

  • Related