需要一些帮助,如何找到儿童使用计数器,累加器和结束哨兵销售的饼干的平均数量(基本编程hwk,yay!)。我有一个问题,弄清楚为什么普通的盒子打印出错误的数字。
例如:
Program result prints out -5 averageBoxes when that's clearly not right...
{
int numBoxes,
// Number of boxes of cookies sold by one child
totalBoxes = 0, // Accumulates total boxes sold by the entire troop
numSeller = 1; // Counts the number of children selling cookies
double averageBoxes; // Average number of boxes sold per child
// Write code to initialize the totalBoxes accumulator to O and
// The numSeller counter to 1.
cout << "**** Cookie Sales Information ****\n";
// Get the first input
cout << "Enter number of boxes of cookies sold by seller " << numSeller
<< " (or -1 to quit): ";
cin >> numBoxes;
// Write code to start a while loop that loops while numBoxes
// is not equal to -1, the sentinel value.
while(numBoxes != -1)
{
// Write code to add numBoxes to the totalBoxes accumlator.
// Write code to add 1 to the numSeller counter.
totalBoxes += numBoxes;
numSeller++;
// Write code to prompt for and input the number of boxes
// sold by the next seller.
cout << "Enter the number of boxes sold by girl scout # " << numSeller << ": ";
cin >> numBoxes;
}
// When the loop is exited, the value stored in the numSeller counter
// will be one more than the actual number of sellers. So write code
// to adjust it to the actual number of sellers.
numSeller = numSeller - 1;
if(numSeller == 0) // If true, -1 was the very first entry
cout << "\nNo boxes were sold.\n";
else
{ // Write code to assign averageBoxes the computed average number
// of boxes sold per seller.
// Write code to print out the number of sellers and average number
// of boxes sold per seller.
averageBoxes += numSeller / numBoxes;
cout << "The average number of boxes sold by the " << numSeller << " sellers was " << averageBoxes << endl;
}
return 0;
}
它可能是一个简单的解决方案,但任何帮助都将不胜感激,谢谢!
答案 0 :(得分:1)
您离开double averageBoxes;
未初始化(它有一个不确定的值,而+=
只会产生另一个不确定的值。)
您应该将其中一个操作数(或两者)强制转换为浮点类型,因此numSeller / numBoxes
的结果是浮点类型:
averageBoxes += numSeller / static_cast<double>(numBoxes);
修改强>
好的,你在上面的表达式中使用了错误的变量(由于它们的名字很容易这样做)。它应该是:
averageBoxes += totalBoxes / static_cast<double>(numSeller);
也许只是不要在程序的顶部声明你的变量(不给它们一个值)。在你第一次使用它们时声明它们:
// += wasn't needed in any case
double averageBoxes = totalBoxes / static_cast<double>(numSeller);