嵌套循环的新增内容
New to nested loops
我遇到了一个问题,如果用户输入Y
以获得另一个集合,计数会继续增加而不是在输出中重置。
在 for 循环之外,应该打印出当前集合的总数,但是一旦我继续处理更多集合,总数就会变成所有集合的运行总计,而不是集合的单个计数
所以我的问题是,有没有办法将计数"重置"为零,而不必再次将它们分配给0
。
遇到了一个问题,我也无法更新设置计数,我尝试将其放入循环中,但没有任何反应。
#include <iomanip>
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int UPPER_VALUE = 100;
const int LOWER_VALUE = 50;
const int NUMBER_OF_VALUES = 10;
int main()
{
srand(time(0));
char userChoice = 'y';
int less60Count = 0,
in60Count = 0,
in70Count = 0,
in80Count = 0,
above90Count = 0,
i = 0,
randomNum = 0,
setCount = 1;
while(tolower(userChoice) == 'y')
{
cout << "Set " << setCount << endl;
for(i = 0; i < NUMBER_OF_VALUES; i++)
{
randomNum = LOWER_VALUE + ( rand() % (UPPER_VALUE - LOWER_VALUE +1));
if(randomNum < 60)
less60Count++;
else if(randomNum < 70)
in60Count++;
else if(randomNum < 80)
in70Count++;
else if(randomNum < 90)
in80Count++;
else
above90Count++;
cout << randomNum << endl;
}
setCount++;
cout << "n90s + count: " << above90Count << " "
<< "80s count: " << in80Count << " "
<< "70s count: " << in70Count << " "
<< "60s count: " << in60Count << " "
<< "Less than 60s: " << less60Count << endl << endl;
cout << "Another one? ";
cin >> userChoice;
if(tolower(userChoice == 'n'))
cout << "GoodBye!" << endl;
}
return 0;
}
通过将计数器移动到while scope
,它们将在每次迭代时设置为 0。
int i = 0, randomNum = 0, setCount = 1;
while (tolower(userChoice) == 'y')
{
int less60Count = 0,
in60Count = 0,
in70Count = 0,
in80Count = 0,
above90Count = 0;
}
或者手动将它们设置为 0。
if (tolower(userChoice) == 'n')
cout << "GoodBye!" << endl;
else
{
less60Count = 0,
in60Count = 0,
in70Count = 0,
in80Count = 0,
above90Count = 0;
}
相关文章:
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 了解嵌套循环打印星号图案
- 无法掌握嵌套循环的写作技巧
- 在 c++ 中实现嵌套循环的更短方法吗?
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 毕达哥拉斯三重嵌套循环误解
- T(n) 表示嵌套循环
- 2 个嵌套循环的时间复杂度
- 嵌套循环背后的逻辑
- 使用 %s C++嵌套循环
- 嵌套循环和重复迭代器
- 如何在 c++ 下使用嵌套循环和正则表达式降低时间复杂度?
- C++在乘法图中放置随机值(嵌套循环)
- 如何使用 OpenMP 减少嵌套循环?
- 为什么使用 2 个嵌套循环 O(n^2) 复杂度来解决二和问题,当只改变循环计数器逻辑时运行得更快?
- 学习嵌套循环C++与示例混淆
- 如何在CUDA中嵌套循环
- std::vector上的嵌套循环
- 嵌套循环在重新函数内未正常运行
- 嵌套循环的新增内容