Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Random Not Random | Data Types and Arrays
C++ Intermediate | Mobile-Friendly

bookRandom Not Random

The random we made in the previous chapter is not random values. You can run your program twice and see that nothing changes.

For this purpose, you can use the function srand(), which sets the seed value, the number, which will be the breakpoint for the program to get a random value. For instance:

12
srand(42); cout << rand();
copy

Wait, we used a random value in the program to generate a random value? It’s not the best idea for the seed parameter. To avoid such problems, you can use the time displayed on your computer as the seed. The procedure is not so complicated. You need only use time(0) in srand() function and add ctime to your includes.

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

int main () {
    srand(time(0));
    cout << rand();

    return 0;
}

Remember, you should use the function srand() only once to set the seed value.

question mark

Which lines of code do you need to make truly random values?

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 5

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Suggested prompts:

Still meg spørsmål om dette emnet

Oppsummer dette kapittelet

Vis eksempler fra virkeligheten

Awesome!

Completion rate improved to 2.94

bookRandom Not Random

Sveip for å vise menyen

The random we made in the previous chapter is not random values. You can run your program twice and see that nothing changes.

For this purpose, you can use the function srand(), which sets the seed value, the number, which will be the breakpoint for the program to get a random value. For instance:

12
srand(42); cout << rand();
copy

Wait, we used a random value in the program to generate a random value? It’s not the best idea for the seed parameter. To avoid such problems, you can use the time displayed on your computer as the seed. The procedure is not so complicated. You need only use time(0) in srand() function and add ctime to your includes.

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

int main () {
    srand(time(0));
    cout << rand();

    return 0;
}

Remember, you should use the function srand() only once to set the seed value.

question mark

Which lines of code do you need to make truly random values?

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 5
some-alt