(C++)使用while循环计算平均数

(C++) Calculating the average number using while loop

本文关键字:循环 计算 平均数 while 使用 C++      更新时间:2023-10-16

需要一些帮助,了解如何使用计数器、累加器和结束哨兵(基本编程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;
}

这可能是一个简单的解决方案,但任何帮助都将不胜感激,谢谢!

  1. 您未初始化double averageBoxes;(它有一个不确定的值,对它执行+=只会产生另一个不确定性值)。

  2. 您应该将其中一个操作数(或两者)强制转换为浮点类型,因此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);