3

I have written the code:

#include <stdio.h>

int main() {
float avg = 8/3;
printf("Average: %.1f", avg);
return 0;
}

When I run the program, the output is:

Average: 2.0

the output I want is the avg var will be 2.6.

I understood from google this should be the output, but it's not. What am I doing wrong?

Eitan
  • 83
  • 2
  • 7
  • 4
    Instead of `float avg = 8/3;`, try `float avg = 8.0/3.0;` `8` and `3` are integer literals, so `8/3` will do the integer division, which results in `2`, and when you assign that to `avg`, it gets casted to `2.0`. By having them as `8.0` and `3.0` you ensure that they are already floats when the division occurs. – Blaze Jan 23 '19 at 12:39
  • This is perhaps the most common beginner FAQ ever. I would recommend reading the chapter about float numbers in your beginner-level C book. It will address this very bug explicitly. – Lundin Jan 23 '19 at 12:43
  • Exactly, and workaround is to multiply numbers by 1.0, `float avg = 8/(3*1.0)` which will produce float result – Ruli Jan 23 '19 at 12:43
  • 1
    @Blaze: Noting that `8.0` is a `double` constant although the compiler will sort this all out for you. Prefer `8.0f`? – Bathsheba Jan 23 '19 at 12:43
  • @Bathsheba Right, I keep forgetting about that. Thanks for reminding me. – Blaze Jan 23 '19 at 12:46

0 Answers0