c++11 - c++ static_cast returns zero -


this question has answer here:

here 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 function print 0 when should print 30?

because result of calculation : 30.30303030

the result of calculation not 30.30303030 0 because

  1. 60 / 99 calculated. result truncated toward 0 because integer division , result 0
  2. 50 * 0 calculated. result 0.

you should 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) ok because other operands converted double match types, using 50.0 * (60 / 99) isn't because 60 / 99 0.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo