Sign in with
Sign up | Sign in
Your question

C++ static cast won't work

Last response: in Applications
Share
June 24, 2011 3:12:31 AM

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;
}

More about : static cast work

a b L Programming
June 24, 2011 6:28:12 AM

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)
m
0
l
June 29, 2011 2:34:49 PM

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);
m
0
l
Related resources
a b L Programming
June 30, 2011 8:08:41 PM

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.
m
0
l
June 30, 2011 10:31:50 PM

I would have normally but the assignment was about the cast.
m
0
l
!