墨菲马 2021-05-08 13:05 采纳率: 50%
浏览 39
已采纳

如何利用随机数函数数值传递给调用函数里不同的变量于不同随机值?

以下是我的代码,但传回来的值都是同一个数值,一般被调用函数被调用完就释放再调用不应该是重新随机生成数吗?

#include<iostream>
#include<ctime>
using namespace std;
int randnum(int);

int main()
{
    double a, b, c;
    int re=0;
    a = randnum(re);
    b = randnum(re);
    c = randnum(re);
    cout << a << "  " << b << "  " << c << endl;
    system("pause");
}

int randnum(int num)
{
    srand((unsigned)time(NULL));
    num = rand() % 100 + 1;
    return num;
    for (int i = 0; i < 20; i++)
        cout << num << " ";
    cout << endl;
}

运行结果:

  • 写回答

5条回答 默认 最新

  • benbenli 2021-05-08 13:21
    关注

    伪随机数啊。你加时间就是要造成真随机数的假象。但是因为运行时间太接近,所以还没有以假乱真。可以记录上次返回值给srand函数乱真。

    #include<iostream>
    #include<ctime>
    using namespace std;
    int randnum(int);
    
    int main()
    {
        double a, b, c;
        int re=0;
        a = randnum(re);
        b = randnum(re);
        c = randnum(re);
        cout << a << "  " << b << "  " << c << endl;
        system("pause");
    }
    
    int randnum(int num)
    {
        static int previous = 0;
        srand((unsigned)time(NULL) + previous);
        previous = rand();
        num = previous % 100 + 1;
        return num;
        for (int i = 0; i < 20; i++)
            cout << num << " ";
        cout << endl;
    }
    
    //Output
    
    57  81  27 

    附注:求赞助积分和C币。加入CSDN将近20年了。最近几年忙小孩没登录。刚才搜索到一本电子书想下载,需要20积分/C币。已经收到8元了,还差12元。赞助多少都可以。多谢。

     

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?