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;
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 eg (3/5) * 100
(which is 0*100
(which is 0
)), you have eg (3*100)/5
(which is 300/5
(which is 60
)).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.