C ++ random int function

Hello, dear participants of stackoverflow. I recently started learning C ++, today I wrote a little game, but my random function is not working correctly. When I call my random function more than once, it does not regenerate the number instead, it prints the same number again and again. How can I solve this problem without using a loop? Thanks

#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
int rolld6();

int main()
{
    cout<<rolld6()<<endl;
    cout<<rolld6()<<endl;
    system("PAUSE");
    return 0;

}

int rolld6()
{
    srand(time(NULL));
    return rand() % 6 + 1;;
}
+3
source share
3 answers

srand(time(NULL));usually should be done once at the beginning main()and never again.

, , , rolld6 , , .

:

#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <stdlib.h>

int rolld6 (void) {
    return rand() % 6 + 1;
}

int main (void) {
    srand (time (NULL));
    std::cout << rolld6() << std::endl;
    std::cout << rolld6() << std::endl;
    system ("PAUSE");
    return 0;
}

, , - . , . , script, , .

, system() cmd.exe script, , - :

1
5
1
5
1
5

, , , .

+10

. srand(time(NULL)); .

+8

( ) .

srand(time(NULL));

, a, , ,

- ( srand (time (NULL)), ).

int rolld6 (void) {
    return rand() % 6 + 1;;
}

int main (void) {
    srand (time (NULL));
...
//call your function here
}

.

, . , ^^

0
source

Source: https://habr.com/ru/post/1791767/


All Articles