标签:
本文主的主要内容是一些随机算法,主要有四种,下面来详细的介绍:
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int i,j; srand((int)time(0)); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { printf("%d ",rand()); } printf("\n"); } return 0; }
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int i,j; srand((int)time(0)); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { printf("%d ",rand()*100/32767); } printf("\n"); } return 0; }
也可以生成100——200之间的随机数
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int i,j; srand((int)time(0)); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { printf("%d ",rand()/1000+100); } printf("\n"); } return 0; }
#include <stdio.h> double rand0_1(double *r) { double base=256.0; double a=17.0; double b=139.0; double temp1=a*(*r)+b; //printf("%lf",temp1); double temp2=(int)(temp1/base); //得到余数 double temp3=temp1-temp2*base; //printf("%lf\n",temp2); //printf("%lf\n",temp3); *r=temp3; double p=*r/base; return p; } int main() { double r=5.0; printf("output 10 number between 0 and 1:\n"); for (int i = 0; i < 10; i++) { printf("%10.5lf\n",rand0_1(&r)); } return 0; }
#include <stdio.h> double rand0_1(double *r) { double base=256.0; double a=17.0; double b=139.0; double temp1=a*(*r)+b; //printf("%lf",temp1); double temp2=(int)(temp1/base); //得到余数 double temp3=temp1-temp2*base; //printf("%lf\n",temp2); //printf("%lf\n",temp3); *r=temp3; double p=*r/base; return p; } int main() { double m=1.0,n=5.0; double r=5.0; printf("output 10 number between 0 and 1:\n"); for (int i = 0; i < 10; i++) { printf("%10.5lf\n",m+(n-m)*rand0_1(&r)); } return 0; }
#include <stdio.h> #include <math.h> double rand0_1(double *r) { double base=256.0; double a=17.0; double b=139.0; double temp1=a*(*r)+b; //printf("%lf",temp1); double temp2=(int)(temp1/base); //得到余数 double temp3=temp1-temp2*base; //printf("%lf\n",temp2); //printf("%lf\n",temp3); *r=temp3; double p=*r/base; return p; } double random_normality(double u,double t,double *r ,double n) { double total=0.0; double result; for (int i = 0; i < n; i++) { total+=rand0_1(r); } result=u+t*(total-n/2)/sqrt(n/12); return result; } int main() { double r=5.0; double u=2.0; double t=3.5; double n=12; printf("output 10 number between 0 and 1:\n"); for (int i = 0; i < 10; i++) { printf("%10.5lf\n",random_normality(u,t,&r,n)); } return 0; }
上面设计的代码都已经运行通过!
标签:
原文地址:http://www.cnblogs.com/tao-alex/p/5819951.html