Domanda

I'm learning about the static cast command so I made this simple program. The two numbers being divided are Integers so I used a float cast to force it to do floating point division, however when I run the program the result is Integer division with the decimal being truncated. I am coding in visual c++ and using Visual Studio 2013. Thanks for any help :)

void PrintAnwser(Fraction Fract)
{
using namespace std;
float Anwser = static_cast<float>(Fract.firstNumber / Fract.secondNumber);
cout << "The result of " << Fract.firstNumber << " " << "Divided by " <<Fract.secondNumber 
<< " " << "is " << Anwser << endl;
}
È stato utile?

Soluzione

The cast is happening after the (integer) division is completed. You need to cast one of the inputs to a float, so that the division will be floating point:

float Anwser = Fract.firstNumber / static_cast<float>(Fract.secondNumber);

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top