-1

I'm new at programming stuff and i'm practicing with variables, so i made a code in C++ where basically i do something like this:

float a;

a=4/3;

printf("%f", a);
return 0;

i expected to get the result as 1.333, but instead i got 1 as value

But if i do this:

float a, b=4, c=3;

a=b/c;

printf("%f", a);
return 0;

It gives back the right value (1.3333)

can somenone please explain that to me?

Al 8A
  • 17
  • 1

1 Answers1

3

Ah, C++ being less than helpful. This is going to annoy you.

  4 / 3

This is INTEGER math, not floating point. This would work if you did one of these:

  4.0 / 3
  4 / 3.0
  4.0 / 3.0

C++ won't upscale your values to floating point while doing the calculation unless there are floating point values somewhere in the calculation itself.

Joseph Larson
  • 8,530
  • 1
  • 19
  • 36