c++按比例生成随机数

来源:百度知道 编辑:UC知道 时间:2024/09/21 14:30:11
想使生成的随机数中(只生成0和1),生成1的个数不超过总数的百分之10%,应该怎么做,以下代码有什么问题。

int j
char p= 0 + rand()%2;
if (p>=0 && p <= 0.1)
cout<<"j:1"<<endl;
if ( p >0.1 && p <= 1)
cout<<"j:0"<<endl;
cout<<"\n"<<endl;

#include<iostream>
#include <time.h>

using namespace std;

void main()
{
int i,t;
srand(time(NULL));

for(i=0;i<100;i++)
{
t=rand()%10;
if(t)
cout<<0;
else
cout<<1;
}
}

rand 返还的是整数,rand%2返回的是0 或者1.
所以用0.1判断没啥意义,最终输出0和1的概率都是50%。
程序可以修改成这样:
int p= 0 + rand()%10;
if (p==0)
cout<<"1"<<endl;
else
{
cout<<"0"<<endl;

}

cout<<"\n"<<endl;

不过都是伪随机

0.1改成0.5
再看看,前面有没有生成种了?