Val Saven Val Saven - 2 months ago 16
C Question

C. Incorrect division (9/5 = 1 instead of 1.8)

When I divide 9/5 in Python or JS - everything is ok and I get 1.8.

When I'm doing it in C - I get 1. Why not 1.8?

What's wrong with the code?

#include <stdio.h>

int main(void) {
double d = 9 / 5;

printf("%g\n", d);
printf("%f\n", d);

return 0;
}


https://ideone.com/6orBrI

Answer

In c, 9 / 5 takes place in integer arithmetic since both arguments are integral types.

Any remainder is truncated, so you end up with 1.

9.0 / 5 will be evaluated in floating point, since one of the arguments is a double type.

Comments