嵌套循环的新增内容

New to nested loops

本文关键字:新增内 嵌套循环      更新时间:2023-10-16

我遇到了一个问题,如果用户输入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;
}