1
#include <stdio.h>
int main() {
double x = 10.4, y;
int m = 2;
y = x / m;

printf("%.1f\n", y);//5.2
printf("%.1f\n", (double)(7 / 2)); //3.0, why not 3.5 ?
printf("%.1f\n", 3.5f);//3.5
// the last line prints 3.5,
// why its not rounding down to 3.0 ,as it did above ?
}

Can someone explain whats happening here ?

DayTimeCoder
  • 4,294
  • 5
  • 38
  • 61

2 Answers2

3

In the line printf("%.1f\n", (double)(7 / 2));, the order of operations is as follows:

  1. 7/2 = 3
  2. (double)3 = 3.0
  3. printf("%.1f\n", 3.0);// Your problem becomes evident.

To achieve the expected behaviour, change (double)(7 / 2) to 7.0 / 2
(i.e., printf("%.1f\n", 7.0 / 2);then your code will correctly print 3.5).

7/2 divides two ints, thus automatically truncating the result to 3 as is the way with integer division. You then cast the result of the integer division to a double to produce 3.0. All these troubles can be avoided if one of the numbers in a mathematical expression is a double, then the other is implicitly cast to a double, thus producing a double in the result.

Nik
  • 1,780
  • 1
  • 14
  • 23
3

Change printf("%.1f\n", (double)(7 / 2)); to printf("%.1f\n", (double)(7.0 / 2)); to get the desired result. 7.0 makes the result to be double.

s4eed
  • 7,173
  • 9
  • 67
  • 104