随机数函数:rand
普通代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{
for (int i=0; i<10; i++)
cout<<rand()%10<<" ";
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int main()
{
for (int i=0; i<10; i++)
cout<<rand()%10<<" ";
return 0;
}
rand()%后面的数即是随机0-那个数了。
但是,多运行几次后,你会发现:每次运行的结果都是一样的!!
这时候,就要用到srand(),即随机数种子函数。
代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{
srand(time(0));
for (int i=0; i<10; i++)
cout<<rand()%10<<" ";
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int main()
{
srand(time(0));
for (int i=0; i<10; i++)
cout<<rand()%10<<" ";
return 0;
}
只要多一个srand(time(0))就行了。不信你试试