-5

I'm working with an iOS project where I have to do a bit of math. Can anyone explain to me why these two implementations return different results?

float total = 31/30;
NSLog(@"%f", total); // returns 1.00000 in console

float total2 = 31/30.0;
NSLog(@"%f", total2); // returns 1.03333 in console

1 Answers1

0

In the majority of computer languages, division involving two integers will have an integer result, the floor of the real result.

In C division, the type of the result is the type of the most precise number in the calculation. In your first example, both 31 and 30 are integers, and so the result is then the integer 1 which is cast to a float to result in 1.00. In your second example, while 31 is an integer, 30.0 is a literal float, and the calculation has a float result, which is than stored in your variable (1.033333...).

Linuxios
  • 34,849
  • 13
  • 91
  • 116
  • There are a few languages where there's a separate operator for integer division vs float division. I'm thinking Pascal (or at least some versions of it) uses `%` for integer division. – Hot Licks Jan 03 '14 at 20:57
  • @HotLicks: Interesting. There are also some languages, like Common Lisp that avoid this entirely and use rational numbers unless you force them to compute the division. – Linuxios Jan 03 '14 at 21:10
  • The sentence “the type of the result is the type of the most precise number in the calculation” does not reflect the actual clause of the C standard, where it is much clearer that promotions happen on the *operands*. This matters because there is not always a “most precise” type between two types, for instance when adding a 32-bit `int` and a 32-bit `float`. Lastly, in “the majority of computer languages”, the integer division is not the floor but the truncation (towards zero) of the real result. – Pascal Cuoq Jan 03 '14 at 23:22
  • @Hot Licks: It's been a long time now, but I seem to remember that the integer division in Pascal used to be **div**, not **%**? – Thomas Padron-McCarthy Jan 04 '14 at 14:15
  • @ThomasPadron-McCarthy - You may be right, it's been a long time for me too... probably 1985 or so. But I'm pretty sure there was at least one language that used `%`, possibly PL/S. – Hot Licks Jan 04 '14 at 17:32