用户验证循环"挂起"
User validation loop 'hangs'
这是我的源代码:
#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: ";
相关文章:
- 挂起和取消挂起一个文件DLL
- 如何防止C++遗留代码中的挂起指针
- 为什么所有C++编译器都会崩溃或挂起此代码
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- 构建挂起,即使是适度的文件大小
- 循环挂起迭代的 std::擦除 on std::list
- Poco::Net::FTPClientSession 在 open() 方法上挂起 129 秒,如果 ftp 主机不存
- Node.js fs.open() 在尝试打开 4 个以上的命名管道 (FIFO) 后挂起
- 从不同进程中的另一个线程挂起/恢复线程或进程
- Boost (Beast) websocket:同步写入挂起
- 为什么析构函数挂起
- 使用互斥会挂起程序
- 在C++和 Python 程序中使用命名管道的 IPC 挂起
- 设置变量时C++程序挂起
- 第一次尝试使用new动态创建结构数组,程序挂起没有错误
- 从stdin读取时子进程挂起(fork/dup2竞争条件)
- 使用提升线程和循环缓冲区挂起的生产者/使用者
- c++程序由于uint32_t for循环而挂起
- 在for循环初始化时挂起很奇怪
- 用户验证循环"挂起"