This question already has an answer here:
My goal is to output the average of the input number and its reversal.
When I input 974, the result is 726.0 instead of 726.5. I have think about this problem for long time but I still cannot get the answer.
Hope someone can help me. Thank you very much!
#include <stdio.h>
int main(void)
{
int N, D1, D2, D3;
double aver;
scanf("%d", &N);
D1 = N % 10;
D2 = ((N - D1) / 10) % 10;
D3 = (N - D1 - D2) / 100;
aver = (D1*100 + D2*10 + D3 + N) / 2;
printf("%lf", aver);
return 0;
}
In your code, N
, D1
, D2
, D3
, all are int
s, so the calculation
(D1*100 + D2*10 + D3 + N) / 2;
is performed as integer arithmetic and later the result is being promoted to double
. So, the result is just a double
representation of an int
value.
To enforce a floating point arithmatic, either
- Change the operand data type(s) to
double
orfloat
. - Cast at least one operand to
float
.
Just add double
. See below:
#include <stdio.h>
int main(void)
{
int N, D1, D2, D3;
double aver;
scanf("%d", &N);
D1 = N % 10;
D2 = ((N - D1) / 10) % 10;
D3 = (N - D1 - D2) / 100;
aver = (double)(D1*100 + D2*10 + D3 + N) / 2;
printf("%lf", aver);
return 0;
}
Checkout the Running code
来源:https://stackoverflow.com/questions/32816694/an-unexpected-result-about-divide-in-c