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 dividingx
byy
. The return value isx-n*y
, wheren
is the valuex / y
, rounded to the nearest integer. If the absolute value ofx-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 dividingx
byy
. The return value isx - n * y
, wheren
is the quotient ofx / y
, rounded toward zero to an integer.