-3

simple question I assume, but I just stumbled across this:

float y=2+2/3; 

Output: 2

How come float cannot process 2/3? My guess is that float interprets 2/3 as integers. But how come it accepts 2 in the beginning?

awesoon
  • 30,028
  • 9
  • 67
  • 92
Joel
  • 4,537
  • 2
  • 33
  • 53
  • The type of the left hand operand of `=` has nothing whatsoever to with which types that will be used when calculating all sub expressions on the right side of `=`. It merely tells in which type to store the final result once all calculations are done. – Lundin Jan 13 '16 at 09:05

2 Answers2

2

That's integer division. You're basically computing:

float y = 2 + (2 / 3);
float y = 2 + (0    );
float y = 2;

Try:

float y = 2 + 2.0 / 3;
Bill Lynch
  • 76,897
  • 15
  • 123
  • 168
  • Yeah that's what i thought, but how come it allows int numbers such as 2, but not 2/3? Is this just for division? Or does the same happen with multiplication & modulo? – Joel Jan 13 '16 at 06:05
  • This. C reads lines from right to left, so it does not know it is supposed to be float until the calculation is already done. – jpa Jan 13 '16 at 06:05
  • @Joel Yes, it also holds true for multiplication and modulus. – Tim Biegeleisen Jan 13 '16 at 06:06
  • @jpa and Tim, thx! Off to the exam! Just a small thing i noticed this morning. – Joel Jan 13 '16 at 06:08
1
float y = 2 + (float)2 / 3;

Just typecast, it will also work.

Stubborn
  • 752
  • 1
  • 5
  • 19