C++ static cast won't work

Gamerboy

Distinguished
Aug 13, 2010
36
0
18,580
I put the offending cast in bold to make it easier to find. The program runs but it executes int division. Any idea why the cast isn't working?


#include <iostream>

struct Fraction
{
int nNumerator;
int nDenominator;
};

void Multiply(Fraction sF1, Fraction sF2)
{
using namespace std;

cout << static_cast<float> (sF1.nNumerator / sF2.nNumerator)*(sF1.nDenominator / sF2.nDenominator);
}

int main()
{
using namespace std;

Fraction sF1;

cout << "Enter a Numerator: " << endl;
cin >> sF1.nNumerator;
cout << "Enter a Denominator: " << endl << endl;
cin >> sF1.nDenominator;

Fraction sF2;

cout << "Enter another Numerator: " << endl;
cin >> sF2.nNumerator;
cout << "Enter another Denominator: " << endl;
cin >> sF2.nDenominator;

Multiply(sF1, sF2);
return 0;
}
 

Ijack

Distinguished
You are casting the result of the division. You need to cast at least one component in each division (personally I would cast all four numbers). Otherwise you do the integer division, with a resulting integer, and then cast that integer to a float. Not, I think, what you intend.

Actually, I don't think you should use static casts at all, just normal casts:

((float) a / (float) b) * ((float) c / (float) d)
 

rockg06

Distinguished
Jun 27, 2011
7
0
18,520
It seems that it's converting the first division into float, but the second division is remaining an int. So it may convert the whole operation back to an int. I would try either static_cast<float>((a/b)*(c/d)); or if that doesn't work: static_cast<float>(a/b)*static_cast<float>(c/d);
 

Ijack

Distinguished
I don't think that either of those will work (but I can't be bothered to check). You're still doing the division before the cast. Divide an integer by an integer and you get an integer result. You can cast that to a float but it won't magically recover the decimal part.

Actually, the easiest answer is just to declare nNumerator and nDenominater as floats in the first place and forget casts.