rand()随机数生成C++

Mr *_*ade -4 c++ random

我正在尝试使用该rand()函数生成伪随机整数.它的工作原理,但我的问题是它始终为int选择相同的名称.(在这种情况下,它是41.我想如果你把rand()主要的while循环放在85或者什么东西.)

有没有办法来解决这个问题?这是我的代码:

    #include <iostream>
    #include <stdio.h>
    #include <stdlib.h>

    int guess;
    int danse = rand() % 101;

    using namespace std;

    void more(){
    cout << "The number that you need to guess is higher!";

    return;
    }

    void lower(){
    cout << "The number that you need to guess is lower!";

    return;
    }

    int main(){
    while(1){
    cout << "\nGuess a number 0-100: ";
    cin >> guess;

    if (guess > danse){
        lower();
}
    if (guess < danse){
        more();
}

    if (guess == 101){
        break;
}

    if (guess == danse){
        cout << "\nYOU GUESSED IT. ARE YOU A WIZARD?! BECAUSE THAT IS PRETTY NEAT.";
        break;
}
    }
    }
Run Code Online (Sandbox Code Playgroud)

只是一些注意事项:请不要试着告诉我我已经知道的事情,例如,解释为什么我使用void函数,返回.请,也不要试图说服我使用命名空间std; 这是做坏事的"坏"方式.我知道还有其他方法可以做到这一点.我选择不这样做.

谢谢!

sim*_*onc 5

您需要在使用前通过调用srand对随机数生成器进行播种rand.当前时间是一种便宜且简单的方法来选择在程序运行之间变化的种子.

int danse;

int main(){
    srand(time(NULL));
    danse = rand() % 101;
Run Code Online (Sandbox Code Playgroud)