播种随机发生器/打印最大值

时间:2016-03-06 03:01:28

标签: c++

我的作业是找到15个随机数中最大的一个,找到最大值,找到最大值出现在列表中的次数,然后根据时间选择随机数生成器。

我必须使用for循环才能执行此操作。 每次通过循环时,我必须执行以下操作: •生成10到20之间的随机数,将其分配给随机数变量,并打印出来。

•检查它是否大于最大值。如果是新的最大值,则指定为最大值。如果数字等于最大加数计数。

•退出循环时,打印列表中显示的最大值和次数。

我的问题是,如何从循环中打印最大数字,如何在一天中的时间播种发生器,以及我该怎样做?

提前致谢。

到目前为止

代码:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int random_x;
    int k;
    int max;
    int num = 0;
    srand(time(NULL));
    for (int t = 0; t<15; t++)
    {
        int random_x;
        random_x = rand() % 100;
        printf("The random numbers are: %d\n", random_x);
    }

    max = INT_MIN;
    for (k = 1; k <= 10; k++) 
    {
        int random_x;
        random_x = rand() % 100;
        if (num > max) max = num;
    } 
    printf("The largest number of the 15 numbers entered was %d\n\n", max);
}

1 个答案:

答案 0 :(得分:0)

试试这个:

#include <iostream>
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

using namespace std;

int main () {
    // srand seeds the random generator,
    // and here we're passing it the time as well
    srand (time (NULL));

    auto max = 0;
    auto maxCount = 0;

    for (auto i = 0; i < 15; i++) {
        auto n = rand () % 10 + 10;

        // comment this out after you're sure things are working
        cout << "n: " << n << endl;

        if (n > max) {
            max = n;
            maxCount = 0;
        }

        if (n == max) {
            maxCount++;
        }
    }

    cout << "max: " << max << endl << "max occurred " << maxCount << " times" << endl;

    return 0;
}

这是C ++ 11,因此您需要一个C ++ 11编译器。 使用Linux上的g ++编译它:g++ -std=c++11 -o randtest.i386 randtest.cpp