Explicit cast with "static_cast" does not occur

2

According to C ++ How to Program, 8th ed., during the operation of two numbers (eg 10/3) the fractional part of the result is lost before being stored in the variable. For this to be avoided, we can resort to explicit conversion using the static_cast operator. So I wrote the code like this:

#include <iostream>

int main(){
  double flutuante;
  int tres = 3;
  int dez = 10;

  flutuante = static_cast<double> (dez / tres);

  std::cout <<" resultdo: " << flutuante;
}

Waiting as a result: 3,333 ... but the result I get is simply 3.

    
asked by anonymous 20.07.2015 / 12:53

1 answer

1

This happens because the / operator when applied to two integers produces as an integer result. For the operation to return a float you must cast one of the arguments to float .

For example:

#include <iostream>

int main(int argc, char *argv[]){

    double flutuante;
    int tres = 3;
    int dez = 10;

    flutuante = dez / static_cast<double> (tres);

    std::cout <<" resultdo: " << flutuante;

    return 0;
}
    
20.07.2015 / 13:17