用户验证循环"挂起"

User validation loop 'hangs'

本文关键字:挂起 循环 验证 用户      更新时间:2023-10-16

这是我的源代码:

 #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 **** nn";
 // 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结果是"三个卖家平均售出的盒子数量为8个。"这是不正确的,因为输出应该是。。"两名卖家平均售出的盒子数量为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: ";