c++11 - c++ static_cast returns zero -
this question has answer here:
- why division result in 0 instead of decimal? 6 answers
- integer division 0 [duplicate] 1 answer
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
- 60 / 99calculated. result truncated toward 0 because integer division , result 0
- 50 * 0calculated. 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.