C++ static cast won't work

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;
4 answers Last reply
More about static cast work
  1. 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)
  2. 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);
  3. 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.
  4. I would have normally but the assignment was about the cast.
Ask a new question

Read More

Programming Apps