1

I would like to know in which order does the explicit type conversion work and in what area does it work. In the next example I receive different results.

float S = 0;
for (int i = 1; i <= 10; i++)
    for (int j = 3; j <= 20; j++)
        S += (i * j - 5.)/(2. * i + j / 3);

the result is 621.8933

float S = 0;
for (float i = 1; i <= 10; i++)
    for (float j = 3; j <= 20; j++)
        S += (i * j - 5)/(2. * i + j / 3);

S = 607.3105

float S = 0;
for (int i = 1; i <= 10; i++)
    for (int j = 3; j <= 20; j++)
        S += (float)(i * j - 5)/(2 * i + j / 3);

S = 621.8933

float S = 0;
for (int i = 1; i <= 10; i++)
    for (int j = 3; j <= 20; j++)
        S += (i * j - 5)/(2 * i + j / 3.);

S = 607.3105

Obviously the correct result is 607.3105. Why doesn't it promote when I write (float) or multiply by 2., but it works when I divide by 3.? Thanks in advance.

Mary
  • 95
  • 9
  • 2
    Because you are casting the result of `(i * j - 5)/(2 * i + j / 3)` to a `float`. This is too late - truncation has already occurred. You need the promotion before any `int` arithmetic that could cause truncation. – Boris the Spider Jun 09 '14 at 11:43
  • Let's take the first example, where I have (2. * i + j / 3). I thought at first it will multiply i by number of type double, after that divide and add. So at least in these brackets it should have been automatically promoted to type double. Or am I missing something? – Mary Jun 09 '14 at 11:51
  • `j/3` has precedence over `+` and `j` is an `int`... – Boris the Spider Jun 09 '14 at 12:25
  • OK. I thought everything in brackets will automatically promote after multiplication. But it means only two operands can promote. Thanks for help! – Mary Jun 09 '14 at 12:32

1 Answers1

0

Code 1 S += (i * j - 5.)/(2. * i + j / 3);:

  • j is an int, thus complete divisor is int and an implicit cast to int is performed

Code 2 S += (i * j - 5)/(2. * i + j / 3);

  • j, x are floats and all consecutive results are floats too

Code 3 S += (float)(i * j - 5)/(2 * i + j / 3);

  • j is an int, thus complete divisor is int and an implicit cast to int is performed
  • The explicit float- is performed after computing of the divisor

Code 4 S += (i * j - 5)/(2 * i + j / 3.);

  • Due to '3.' the divisor becomes of type 'double'

Note that 3. is a double, 3.f is a float. This results in usage of different precision within the operation.

Th. Thielemann
  • 2,592
  • 1
  • 23
  • 38