An unexpected result about divide in C [duplicate]

别等时光非礼了梦想. 提交于 2019-12-02 10:43:16

问题


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;
}

回答1:


In your code, N, D1, D2, D3, all are ints, 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

  1. Change the operand data type(s) to double or float.
  2. Cast at least one operand to float.



回答2:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!