rand
#include<iostream>#include<string>
#include<math.h>
#include<iomanip>
#include<stdio.h>
#include<ctime>
#include<cstdlib>
using namespace std;
int casual()
{
srand(time(0));
int a = rand() % 6 + 1;
srand(2);
int b = rand() % 6 + 1;
int sum = a + b;
cout<<a<<"+"<<b<<"="<<sum<<endl;
return sum;
}
main()
{
int any = casual();
cout<<any<<endl;
any = casual();
cout<<any<<endl;
any = casual();
cout<<any<<endl;
}
为什么生成不了随机数 C++吗? 嘉岳呀 发表于 2020-10-11 11:00
C++吗?
是 #include<iostream>
#include<string>
#include<math.h>
#include<iomanip>
#include<stdio.h>
#include<ctime>
#include<cstdlib>
using namespace std;
int casual()
{
int a = rand() % 6 + 1;
//srand(2);
int b = rand() % 6 + 1;
int sum = a + b;
cout<<a<<"+"<<b<<"="<<sum<<endl;
return sum;
}
main()
{
srand(time(0)); // 把种子放在主函数里,确保只调用一次
int any = casual();
cout<<any<<endl;
int any1 = casual();
cout<<any1<<endl;
int any2 = casual();
cout<<any2<<endl;
} #include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int casual()
{
int a,b,sum=0;
a = rand() % 6 + 1;
srand(2);
b = rand() % 6 + 1;
sum = a + b;
return sum;
}
int main()
{
int any = casual();
srand(time(0));
cout<<any<<endl;
any = casual();
cout<<any<<endl;
any = casual();
cout<<any<<endl;
return 0;
}
我试了几次,感觉每次出现相同数的几率很大
页:
[1]