-1

C language, stdio.h library

Sample code:

float avg;
avg = 3 / 2;
printf("Average: %.2f", avg);

From the code above I expect the following output:

Average = 1.50

But instead I get:

Average = 1.00

Why is this? And how do I get the correct output?

lefrost
  • 461
  • 5
  • 17

4 Answers4

1

3 and 2 are integers, so the resulting integer i.e. 1 will then cast to float after the division, and you will have 1.00. you have to make them floats, do this:

avg = 3.0 / 2.0;
ganjim
  • 1,234
  • 1
  • 16
  • 30
0

You should use it like this..avg=3.0/2.0 otherwise it's doing integer division. It's truncated to 1 otherwise. (Integer divison truncates, so any fractional part , here .5 is discarded).

A decimal point in a constant indicates that it is floating point. So the result is not truncated.

From standard:-§6.5.5.5

When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.

user2736738
  • 30,591
  • 5
  • 42
  • 56
0
#include <stdio.h>

int main(void) {
float avg;
avg = (float) 3 / 2;
printf("Average: %.2f", avg);

    return 0;
}
anupam691997
  • 310
  • 2
  • 8
  • 3/2 is an integer division and that's why the answer is coming 1.00, convert 3 into float and then perform the division it will give the correct result – anupam691997 Nov 11 '17 at 04:39
0

You are performing integer division there. So the fractional part is discarded.

Try this

float avg;
avg = 3.0 / 2;
printf("Average: %.2f", avg);

By keeping either the numerator or denominator of type float it will perform floating point division.

Frank
  • 9
  • 3