以下是我的代码,但传回来的值都是同一个数值,一般被调用函数被调用完就释放再调用不应该是重新随机生成数吗?
#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;
}
运行结果:
伪随机数啊。你加时间就是要造成真随机数的假象。但是因为运行时间太接近,所以还没有以假乱真。可以记录上次返回值给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元。赞助多少都可以。多谢。
把srand((unsigned)time(NULL));放到a=randnum(re);之前,不要放在函数里
请求大佬给我一点方向
#define _CRT_RAND_S
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
using namespace std;
int randnum()
{
unsigned int num = 0;
rand_s(&num);
num = num % 100 + 1;
return num;
}
int main()
{
int a, b, c;
a = randnum();
b = randnum();
c = randnum();
cout << a << " " << b << " " << c << endl;
return 0;
}
希望对你有帮助:https://blog.csdn.net/it_xiangqiang/category_10581430.html
希望对你有帮助:https://blog.csdn.net/it_xiangqiang/category_10768339.html