抱歉,我是一个非常新手的程序员,只是学习而已。我一直有一个问题。我一直试图让它计算显示最大数字的次数。但是有时它还应该增加一个。我更改了一些变量并将其移动。我被困了大约一个小时。

#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++ - 对于循环和计数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28993188/

10-08 21:34