(C++)使用while循环计算平均数
(C++) Calculating the average number using while loop
需要一些帮助,了解如何使用计数器、累加器和结束哨兵(基本编程hwk,耶!)来查找儿童出售的饼干的平均盒数。我在弄清楚为什么averageBoxes打印出错误的数字时遇到了问题。
例如:
程序结果打印出-5个平均框,当这显然不正确时。。。
{
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;
}
这可能是一个简单的解决方案,但任何帮助都将不胜感激,谢谢!
-
您未初始化
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);
相关文章:
- 当 A 在 for 循环中调用函数 B 时,如何计算函数 A 的空间复杂度?
- 如何编写计算功率的循环
- 在循环条件 i<sqrtN(预先计算)和 i*i<N 中,C++哪个更有效?
- 如果代码包含多个复杂度循环,如何计算复杂度
- C++在不使用pow或循环的情况下计算一个数字的幂
- 计算递归和时的无限循环
- 使用与 openmp C++并行的循环计算矩阵中每一行的最小值
- getline() 在 while 循环条件中如何计算为真或假?
- 为什么 g++ 将计算拉入热循环
- 计算使用 C++ std 函数而不是 for 循环的大 O
- 使用一个WALE循环计算AVG测试得分
- C++ (for) 循环:计算 y=n/(n+1)
- (C++)使用while循环计算平均数
- 尝试使用for循环计算Pi只给出3
- 基本的依偎循环计算1 - 239之间的质数,包括
- 循环计算矩形面积的公式
- c++ 11基于范围的for()循环计算一次或多次
- 使用while循环计算前n个斐波那契数的程序
- 使用while循环计算数学常数e
- 用泰勒方法和循环计算圆周率