在 for 循环中查找问题时遇到困难
Having difficulties locating a problem in the 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;
将整数除以整数会得到一个整数,方法是截断小数部分。
由于您的值小于 1,因此您的结果将始终为零。
可以将操作数强制转换为浮点类型,以获取所需的计算:
(ticPurch.at(i) / (double)totalTics) * 100
然后可能会对这个结果进行四舍五入,因为你似乎想要整数结果:
std::floor((ticPurch.at(i) / (double)totalTics) * 100)
我的首选方法是完全避免浮点(总是很好!),是先乘以计算的分辨率:
(ticPurch.at(i) * 100) / totalTics
这将始终向下舍入,因此请注意,如果您决定使用std::round
(或std::ceil
)而不是上面示例中的std::floor
。如果需要,算术技巧可以模仿这些。
现在,而不是例如(3/5) * 100
(这是0*100
(这是0
)),你有例如(3*100)/5
(这是300/5
(这是60
))。
相关文章:
- 编译包含字符串的代码时遇到问题
- 在顶点着色器中使用 OpenGl 的未声明标识符,我在顶点着色器中绘制三角形时遇到问题
- 从其他类访问类时遇到问题
- 使用静态成员声明类时遇到问题
- C++ 填充数组时遇到问题
- 在将字符串放入字符串向量时遇到问题?
- 余数除法和不允许除以零 (c++) 时遇到问题
- 我在C++中使用 getline() 函数时遇到问题
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 在我的四叉树实现中遇到问题
- 在 c++ 中循环遍历数组时遇到问题
- 使用 MinGW 在 Windows 上构建 GLEW 时遇到问题
- 编译 Cilk Plus 程序时遇到问题
- 存储另一个函数返回的布尔数组时遇到问题
- 我在 OpenGL 中显示图像时遇到问题
- 我在解决此错误时遇到问题.我正在努力在主函数中传递数组
- 在 for 循环中更新两个变量时遇到问题C++
- 为什么我的程序在打开网络设备时遇到问题
- 在 Tensorflow C++ 中使用 FIFOQueue 时遇到问题
- 为什么我在虚幻引擎中的多态性和接口方面遇到问题?