c++ - 难以定位 for 循环中的问题

标签 c++ for-loop

我正在编写一个程序,用户可以在其中输入参赛者的姓名并像比赛门票一样购买。我试图计算出每个参赛者获胜的百分比机会,但由于某种原因它返回零,这是代码

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;

最佳答案

整数除以整数 gives you an integer , 通过截断小数部分。

由于您的值小于 1,因此您的结果将始终为零。

您可以将操作数转换为浮点类型以获得您想要的计算:

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

然后可能会舍入这个结果,因为您似乎想要整数结果:

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

我的首选方法是完全避免 float (总是很好!),首先乘以您的计算分辨率:

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

这将始终向下舍入,因此如果您决定使用 std::round(或 std::ceil ) 而不是上面示例中的 std::floor。如果需要,算术技巧可以模仿那些。

现在,而不是例如(3/5) * 100(即 0*100(即 0)),例如(3*100)/5(即 300/5(即 60))。

关于c++ - 难以定位 for 循环中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53049422/

相关文章:

c++ - 字符的子序列

python - 在 Pandas 数据框中一次更改一行

for-loop - 如何使用 DrawerHeader 和 ListView.builder 构建抽屉

python - for 循环 Python 3.5。为我辅导的学生创建测验

python - 退出 for 循环

c - For循环条件

c++ - std::vector 的容量是如何确定的

c++ - 在 Windows XP 中多次启动程序 + DLL 时出现问题?

c++ - 限制嵌套结构中的构造函数范围

c++ - C++ 标准是否要求无符号整数的最大值为 2^N-1 形式?