-3
有人可以看看这段代码,并帮我弄清楚有什么问题吗?while循环来检查C++的错误?
#include <iostream>
#include <vector>
using namespace std;
int numExercise;
cout << "Enter num exercises: ";
cin >> numExercise;
vector <float> weight;
float sumWeight = 0;
while(sumWeight != 1)
{
// Loop to assign a weighted value to each exercise.
for (int i = 0; i < numExercise; i++)
{
float weightEntered;
cout << "\n Assignment " << i + 1 << " : ";
cin >> weightEntered;
//Divide percentage by 100 to get decimals.
weightEntered /= 100;
//Send the data back to the vector.
weight.push_back(weightEntered);
}
// Loop to error check if the total weights isn't 100.
for (int i = 0; i < numExercise; i++)
{
sumWeight += weight[i];
}
cout << sumWeight << endl;
sumWeight = 0;
//if (sumWeight != 1)
cout << "\n\t\tError, total weights should be 100" << endl;
}
因此,在这种代码我输入一定量的分配和每个分配的权重必须超过100%...例如输入3个分配和每个权重是30,30,40后输入权重代码将每个权重除以100得到十进制值(我在其余代码中使用它来计算其他内容)。
问题是,我试图确保无论用户输入什么加起来最多为100,否则他们必须再次输入数字。当我运行这个循环并输入错误的数字时,它会要求我再次输入它们,但它没有经过第二次输入的权重总和,所以显示的数字仍然是第一个总和。我究竟做错了什么??
***请看看这段代码,并帮助我弄清楚什么是错?***请学习如何使用调试器。从长远来看,这将比您为您的代码调试更有帮助。 – drescherjm
解决这些问题的正确工具是您的调试器。在*堆栈溢出问题之前,您应该逐行执行您的代码。如需更多帮助,请阅读[如何调试小程序(由Eric Lippert撰写)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您应该\编辑您的问题,以包含一个[最小,完整和可验证](http://stackoverflow.com/help/mcve)示例,该示例再现了您的问题,以及您在调试器。 –
如果用户输入小数值(例如10.3,56.7等),则此代码注定失败。原因是,您无法保证这些数字在添加时会精确等于1.0(或100)尽管你可能认为他们会。原因是浮点数不确切。 – PaulMcKenzie