【发布时间】:2021-05-29 10:54:51
【问题描述】:
我正在尝试编写一个程序来计算用户从 while 循环中输入特定数字的次数。思路如下:
#include <iostream>
#include <ctime>
using namespace std;
int main() {
bool progLoop = true;
int Number;
char response;
while (progLoop == true)
{
cout << "Please enter a number: " << endl; \
cin >> Number;
cout << "Number collected!" << endl;
cout << "Number of times that number has been entered: " << endl; //IDK how to do this part which is what I'm looking for.
cout << "Do you want to enter another number?" << endl;
cin >> response;
if (response == 'y')
{
progLoop == true;
}
else if(response == 'n')
{
progLoop == false;
}
}
}
我正在寻找一种方法来存储特定数字已输入程序的次数的值。如果有任何问题想澄清一下!谢谢! (修改我的代码会很棒!)
【问题讨论】:
-
一种方法是创建一个向量,每次输入新数字时,都会将其推回向量中。然后您可以在需要检查时
std::count该号码。另一种方法是使用std::unordered_map。 -
顺便说一句,你不小心在循环中写了
progLoop == true;和progLoop == false;,这意味着即使你输入n,循环仍然会运行。 -
我刚刚发布了使用 unordered_map 的方式,恕我直言,性能更好
-
您不需要布尔值,只需将字符集设置为 'y'
-
你也应该有括号之间的用法(y/n)