我正在编写一个程序,用户输入参赛者的名字,并购买比赛门票.我试图弄清楚每个参赛者获胜的几率,但由于某种原因它会返回零,这是代码
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;
Run Code Online (Sandbox Code Playgroud)
由于您的值小于1,因此结果将始终为零.
您可以将操作数强制转换为浮点类型以获得所需的计算:
(ticPurch.at(i) / (double)totalTics) * 100
Run Code Online (Sandbox Code Playgroud)
然后可能围绕这个结果,因为你似乎想要整数结果:
std::floor((ticPurch.at(i) / (double)totalTics) * 100)
Run Code Online (Sandbox Code Playgroud)
我的首选方法,从而避免了浮点完全(!总是好的),是繁衍到您的计算解决第一:
(ticPurch.at(i) * 100) / totalTics
Run Code Online (Sandbox Code Playgroud)
这将始终向下舍入,因此请注意,如果您决定使用std::round
(或std::ceil
),而不是std::floor
在上面的示例中.如果需要,算术技巧可以模仿那些.
现在,而不是eg (3/5) * 100
(即0*100
(是0
)),你有eg (3*100)/5
(即300/5
(是60
)).