用户验证循环'挂起'

时间:2015-06-24 15:30:56

标签: c++

这是我的源代码:

 #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 -10 24 -1 输出为&#34; 3个卖家的平均售出的盒子数量是8个。&#34; 这是不正确的,因为输出应该 .. &#34; 2个卖家的平均售出的盒子数量为17个。 我已经尝试了各种while循环来在原始while循环中进行用户验证但它挂起并且如果我输入-1以下的任何内容则永远不会去任何地方。 我猜测我的逻辑错了,但我真的无法想出这个。

谢谢。

1 个答案:

答案 0 :(得分:2)

您可以通过这种方式考虑问题: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: ";