0

I am writing a program where a user inputs the name of contestants and buys like a ticket for a competition. I am trying to figure out the percent chance for each contestant to win but for some reason its returning zero, here's the code

for(int i = 0; i < ticPurch.size(); i++){
    totalTics = ticPurch[i] + totalTics;                                              //Figuring out total amount of ticket bought
}
    cout << totalTics;

for (int i = 0; i < names.size(); i++){
    cout << "Contenstant "  << "   Chance of winning " << endl; 
    cout << names[i] << "   " << ((ticPurch.at(i))/(totalTics)) * 100 << " % " << endl; //Figuring out the total chance of winning 

}
    ticPurch is a vector of the the tickets each contestant bought and names is a vector for the contestants name. For some reason the percent is always returning zero and I don't know why

 return 0;
MATH ASKER
  • 53
  • 9
  • 2
    what type is `totalTics`? And what type is `ticPurch.at(i)`? Hint: if they're both `int`, the result of that division will also be an `int`. – scohe001 Oct 29 '18 at 16:02
  • 1
    What is ticPurch? What is totalTics? If you are trying to divide integers, you'll get an integer. 3/4 gives 0. Use `double` if that is the case – Aykhan Hagverdili Oct 29 '18 at 16:05

1 Answers1

7

Dividing an integer by an integer gives you an integer, by truncation of the fractional part.

Since your values are less than one, your result will always be zero.

You could cast an operand to a floating-point type to get the calculation you wanted:

(ticPurch.at(i) / (double)totalTics) * 100

Then probably round this result, since you seem to want whole number results:

std::floor((ticPurch.at(i) / (double)totalTics) * 100)

My preferred approach, which avoids floating-point entirely (always nice!), is to multiply to the resolution of your calculation first:

(ticPurch.at(i) * 100) / totalTics

This will always round down, so be aware of that if you decided to go with, say, std::round (or std::ceil) instead of std::floor in the example above. Arithmetic trickery can mimic those if needs be.

Now, instead of e.g. (3/5) * 100 (which is 0*100 (which is 0)), you have e.g. (3*100)/5 (which is 300/5 (which is 60)).

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055