Explicit conversion with "static_cast" does not occur

Asked

Viewed 79 times

2

According to the C++ How to Program, 8th ed., during the operation of two numbers (e.g.: 10/3) the fractional part of the resuscitation is lost before it is stored in the variable . For this to be avoided, we can resort to explicit conversion using the operator static_cast. 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 amount I get is simply 3.

1 answer

1

This happens because the operator / when applied to two integers produces as a result an integer. For the operation to return one 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.