Stella Jin
Stella Jin

Reputation: 15

c++ beginner generate random numbers using while loop

generate 10 random integers in the range [- 50, 50 ], then outputs the largest among them. What i have tried is

#include <iostream>
#include <ctime>

using namespace std;

int main(){

    int startNum = -50;
    int endNum = 50;
    int rand = 0;
    int result = 0;

    srand(time(0));
    rand = (rand % (endNum - startNum +1 ) +startNum);
    int i = 0;
    int largestNum = 0;

    while (i <9){
        result = rand; 
        if (result > largestNum){
            largestNum = rand;
                i++;
        }

    }
        cout << "the largest number is " << largestNum << endl; 

    system("pause");
    return 0;
}

Upvotes: 0

Views: 2749

Answers (2)

bolov
bolov

Reputation: 75904

rand() is considered bad, mostly because you can't really generate an uniform distribution. I strongly recommend C++ random lib. Also you are not using rand(). I don't know what you are doing there.

Anyway, here is an elegant solution:

#include <iostream>
#include <random>
#include <algorithm>
#include <limits>

int main()
{
    std::random_device rd{};
    std::mt19937 eng{rd()}; // or std::default_random_engine e{rd()};
    std::uniform_int_distribution<int> dist{-50, 50};

    int largestNum = std::numeric_limits<int>::min();

    for (int i = 0; i < 10; ++i)
    {
        largestNum = std::max(largestNum, dist(eng));
    }

    std::cout << "the largest number is " << largestNum  << std::endl;
}

Upvotes: 1

Zolt&#225;n
Zolt&#225;n

Reputation: 708

Similar questions have been already aswered but here's a complete working example for you:

int main()
{
    int i=0;
    int startNum = -50;
    int endNum = 50;
    int maxNum = startNum;

    std::cout << "The 10 random numbers:\n";
    while (i < 10)
    {
        int num = (rand() % (endNum - startNum + 1)) + startNum; 
        if (num > maxNum)
            maxNum = num;
        std::cout << num << "\n";
        ++i;
    }
    std::cout << "The largest number is: " << maxNum << "\n";

    return 0;
}

Although I don't really recommend using rand with loops. That's not the c++ way to do it. Check out this answer.

Upvotes: 0

Related Questions