gpt4 book ai didi

c++ - 用户验证循环 'hangs'

转载 作者:行者123 更新时间:2023-11-28 02:25:04 25 4
gpt4 key购买 nike

这是我的源代码:

 #include <iostream>
using namespace std;

int main()
{
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 ACCUMLATOR TO 0 AND
// THE numSeller COUNTER TO 1.


cout << " **** Cookie Sales Information **** \n\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 ACCUMULATOR.
// WRITE CODE TO ADD 1 TO THE numSeller COUNTER.


totalBoxes += numBoxes;

numSeller++;
cout << "Please enter amount of boxes sold by the next seller: ";
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 -= 1;


if (numSeller == 0)
cout << "\nNo boxes were sold.\n";
else
{
// WRITE CODE TO ASSIGN averageBoxes THE COMPUTED AVERAGE NUMBER
// OF BOXES SOLD PER SELLER.
averageBoxes = (double)totalBoxes / (double)numSeller;
// WRITE CODE TO PRINT OUT THE NUMBER OF SELLERS AND AVERAGE NUMBER
// OF BOXES SOLD PER SELLER.
cout << "The average number of boxes sold by the " << numSeller << " sellers was " << averageBoxes << endl;
}

return 0;
}

该程序接受用户的输入,将添加的金额加在一起直到达到标记值,然后显示卖家的数量和所述卖家的平均售出箱数。我的问题是为用户验证添加另一个 while 循环。如果我进入..10-1024-1输出为“3 位卖家平均售出的箱子数量为 8 箱。”这是不正确的,因为输出应该是..“这 2 位卖家平均卖出了 17 盒。我已经尝试了各种 while 循环以在原始 while 循环内进行用户验证,但是如果我输入低于 -1 的任何内容,它就会挂起并且永远不会去任何地方。我猜我的逻辑是错误的,但我真的无法弄清楚这一点。

谢谢。

最佳答案

您可以这样想这个问题:while 循环的每次迭代都应该只要求用户输入一次。每次您要求用户输入时,您可以使用该输入或丢弃它。所以你可以拿这个代码:

totalBoxes += numBoxes;

numSeller++;
cout << "Please enter amount of boxes sold by the next seller: ";

并用这样的东西替换它:

if (numBoxes >= 0)
{
totalBoxes += numBoxes;
numSeller++;
}
else
{
cout << "That is not a valid number of boxes. Naughty.\n"
}
cout << "Please enter amount of boxes sold by the next seller: ";

关于c++ - 用户验证循环 'hangs',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31030789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com