gpt4 book ai didi

c++ - For 循环和计数

转载 作者:行者123 更新时间:2023-11-28 06:23:14 25 4
gpt4 key购买 nike

对不起,我是一个非常新手的程序员,只是在学习。我一直遇到一个问题。我一直试图让这个来计算最大数字显示的次数。但有时它比它应该多一个。我更改了一些变量并将其移动。我已经被困了大约一个小时。

#include <iostream>
#include <ctime>
using namespace std;

int main()
{
int largeNumCount = 0;
int largeNum = 1;
srand(unsigned(time(0)));
for (int x = 1; x <= 20; x++)
{
int randNum = (rand() % 10) + 1;
cout << randNum << " ";
if (largeNum <= randNum)
{
largeNum = randNum;
largeNumCount = 1;
}
if (largeNum == randNum)
{
largeNumCount++;
}
}

cout << "\n\nThe largest number: " << largeNum << " was found " << largeNumCount << " time(s)\n\n";
system("pause");
return 0;
}

最佳答案

试试这个:

if ( randNum > largeNum )
{
largeNum = randNum;
largeNumCount = 1;
}
else if ( randNum == largeNum )
{
++largeNumCount;
}

关于c++ - For 循环和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28993188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com