An unexpected result about divide in C [duplicate]

人走茶凉 提交于 2019-12-02 07:41:57

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.

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

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