1

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;
}
Codor
  • 17,447
  • 9
  • 29
  • 56
kenchan13
  • 121
  • 1
  • 5
  • 3
    An `int` divided by an `int` is an `int`. `(D1*100 + D2*10 + D3 + N)` is an `int`. If you want `double` division, divide it by `2.0` instead of `2`. – Ry- Sep 28 '15 at 06:15
  • Better duplicate: http://stackoverflow.com/questions/2345902/division-result-is-always-zero – Matteo Italia Sep 28 '15 at 06:21

2 Answers2

4

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.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

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

Shahzad Barkati
  • 2,532
  • 6
  • 25
  • 33