-3

Here is my problem:

#include <stdio.h>
#include <math.h>

int main()
{

    int n = static_cast<int>(50 * (60 / 99));

    printf("Floor: %d\n", n);

    return 0;
}

Why does the function print 0 when it should print 30?

Because the result of calculation is : 30.30303030

coyotte508
  • 9,175
  • 6
  • 44
  • 63
  • its more like 0.6 .. how can make the hole calculation to return 30? – Ursache Bogdan Jun 02 '16 at 00:19
  • 1
    60/99 is evaluated as integer math, so the result is 0. Change either value to floating point: ` 60.0f / 99.f` will do is one way to do the job. – Jerry Coffin Jun 02 '16 at 00:20
  • One way to archive this is using another language such as JavaScript, or a language you develop that supports `static_cast`, division that always return floating-point value, and all of other features you want. – MikeCAT Jun 02 '16 at 00:21
  • Downvoted for lack of research effort. The answer to this question is trivial to find, both on SO and in other resources. – Baum mit Augen Jun 02 '16 at 00:40
  • too bad i could not show you my search history... i did search it for like 2 hours... – Ursache Bogdan Jun 02 '16 at 00:47
  • You may do `(50 * 60) / 99` to stick with integers. – Jarod42 Jun 02 '16 at 01:07

1 Answers1

1

The result of calculation is not 30.30303030 but 0 because

  1. 60 / 99 is calculated. The result is truncated toward zero because this is integer division and the result is 0
  2. 50 * 0 is calculated. The result is 0.

You should do the calculation using double.

#include <stdio.h>
#include <math.h>

int main()
{

    int n = static_cast<int>(50.0 * (60.0 / 99.0));

    printf("Floor: %d\n", n);

    return 0;
}

Using 50 * (60.0 / 99) or 50 * (60 / 99.0) instead of 50.0 * (60.0 / 99.0) is also OK because other operands will be converted to double to match types, but using 50.0 * (60 / 99) isn't good because 60 / 99 is 0.

coyotte508
  • 9,175
  • 6
  • 44
  • 63
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • Thank you so much :D I didn't think double will help :D problem solved. Now I can code the rest of the system easy. Since 50 is a variable PlayerLevel. – Ursache Bogdan Jun 02 '16 at 00:24