3

Possible Duplicate:
C++ int float problem

I'm simply trying to calculate and print a percentage, and although the variables being used in calculation are displaying correctly, the final percentage keeps showing as "0". Here is the code:

 int iWageredTot = iBet * 4 * iGames;
    cout<<"Total Won: "<<iBankRoll<<endl;
    cout<<"Wagered total: "<<iWageredTot<<endl;
    float iPercent;
    iPercent = iBankRoll / iWageredTot;
    cout<<iPercent<<"% edge\n"<<endl;

And this is the output:

Total won: -770
Wagered Total: 4000
0% edge

I tried using int, float, and double. What am I missing? Thank you for any help.

Community
  • 1
  • 1
chuckieDub
  • 1,767
  • 9
  • 27
  • 46

3 Answers3

3

Maybe

iPercent = (float)iBankRoll / iWageredTot;

If iBankRoll and iWageredTot are declared as int, iBankRoll / iWageredTot will also be an int which will be then converted to float, but if it's initially 0, you'll end up with a float 0.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • And maybe he should be using `double` rather than `float`. (`double` is the default floating point type in C++. While it's not an error to use `float`, it sends the wrong message to the reader, since `float` is normally only used when there is a special reason not to use `double`.) – James Kanze Dec 20 '12 at 14:46
2

You need to convert one of the operands of / to a floating point type, otherwise integer division will be performed. You also are only calculating a fraction at the moment. If you want a percentage, you need to multiply by 100.

iPercent = (static_cast<float>(iBankRoll) / iWageredTot) * 100;
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
1

You are performing (what looks like) integer division, and then assigning the result of that operation to a float. That's why the float is zero.

To correct this, do floating-point arithmetic instead:

iPercent = (float)iBankRoll/(float)iWageredTot;
John Dibling
  • 99,718
  • 31
  • 186
  • 324