-3

Why does this expression give me an output of zero?

float x = ((1000)/(24 * 60 * 60));

Breaking this into two parts, gives the correct result:

float x = (1000);
x /= (24 * 60 * 60);

2 Answers2

4

The statement

float x = ((1000)/(24 * 60 * 60));

does the following:

  1. Declares a variable x of type float.
  2. Evaluates ((1000)/(24 * 60 * 60)).
    1. Evaluates 24*60*60 which is 86400.
    2. Evaluates 1000/86400 which is 0.
  3. Assigns the result of that (which is 0) to x.

In the second step, ((1000)/(24 * 60 * 60)) is zero - the division is integer division, because both operands are integers. The fact that the result gets assigned to a floating point variable later makes no difference.

The simplest fix is to make sure either side of the division is a floating-point number, so it will use floating-point division. For example, you could change 1000 to 1000.0f.

user253751
  • 57,427
  • 7
  • 48
  • 90
0

See this answer, it will give you the correct output

#include <stdio.h>

int main(void) {
    float x = (float)1000/(24 * 60 * 60);
    printf("%f",x);
    return 0;
}

Output: 0.011574 Output can also be seen: http://ideone.com/6bMp9r

Jaffer Wilson
  • 7,029
  • 10
  • 62
  • 139