随机数赋值,srand()放在循环体和循环体外的区别
2012-12-06 16:48
507 查看
这是一段由下面一段代码引发的血案:
这段代码的作者抱怨srand()函数放到循环体内部一直无输出,但实际上会有输出的,只不过需要点时间。下面的是要讨论的重点,首先先看几个代码:
代码1:
代码2:
代码3:
rand函数是一个伪随机数列。在没有srand的情况下,每次生成的序列都是一样的。
而运行了srand(n);以后在n相同的情况下,rand每次生成的序列还是一样的。
就是说,如果每次运行一次srand(n);再运行rand,生成的第一个数都是一样的。(time(NULL),是以秒为单位,一秒钟数字增加一个)
#include<stdio.h> #include<time.h> #include<stdlib.h> #define counter 1 #define bool int #define true 1 #define false 0 int main() { bool flag[100]; bool light=false; int count=0; int times=0; int temp; for(temp=0;temp<100;temp++) flag[temp]=false; //srand(time(NULL)); while(true) { srand(time(NULL)); temp=rand()%100; times++; if((flag[temp]==false)&&(light==false)&&(temp!=counter)) { flag[temp]=true; printf("%d ",temp); light=true; } if((temp==counter)&&(light==true)) { light=false; count++; } //printf("times:%d\n",times); srand丢循环体内,可执行。 if(count==99) break; } printf("times:%ddays later:\n",times); }
这段代码的作者抱怨srand()函数放到循环体内部一直无输出,但实际上会有输出的,只不过需要点时间。下面的是要讨论的重点,首先先看几个代码:
代码1:
/*结果永远是1740948824*/ #include<stdio.h> #include<stdlib.h> int main() { int i=0; for(i=0;i<10;i++) printf("%d",rand()%10); printf("\n"); return 0; }
代码2:
/*加了srand以后,结果永远是1924762269,但是,和原来的1740948824不一样了*/ #include<stdio.h> #include<stdlib.h> int main() { int i=0; srand(10); //加了个srand for(i=0;i<10;i++) printf("%d",rand()%10); printf("\n"); return 0; }
代码3:
/*把srand放在循环里,输出永远是1111111111*/ #include<stdio.h> #include<stdlib.h> int main() { int i=0; //srand(10); //这条去掉 for(i=0;i<10;i++) { srand(10); //放在循环里 printf("%d",rand()%10); } printf("\n"); return 0; }
rand函数是一个伪随机数列。在没有srand的情况下,每次生成的序列都是一样的。
而运行了srand(n);以后在n相同的情况下,rand每次生成的序列还是一样的。
就是说,如果每次运行一次srand(n);再运行rand,生成的第一个数都是一样的。(time(NULL),是以秒为单位,一秒钟数字增加一个)
相关文章推荐
- js跳出循环的方法区别(break,continue,return)区分函数体内和循环体内的区别
- java中new一个对象放在循环体里面与外面的区别
- try catch放在循环内外的区别
- ios给NSMutableDictionary循环赋值的两种方式,在循环内初始化NSMutableDictionary和在循环外初始化NSMutableDictionary有何区别?(已解决)
- 循环体外和循环体内定义变量的一点思考
- 随机数 rand()与srand()的区别
- Java: 变量声明在循环体内还是循环体外的争论
- 对象创建语句放在循环外和循环内的区别
- foreach循环初始化值变量放在内层循环体的外边,赋予初始值
- java中new一个对象放在循环体里面与外面的区别
- javascript放在head和body的区别(w3c建议放在head标签中)
- sql server中SELECT 与 SET 赋值的区别
- C# 循环结构while,do-while和for的区别以及跳转语句
- sqlserver 循环赋值变量
- (Verilog HDL)阻塞赋值和非阻塞赋值的区别和使用
- java中String new和直接赋值的区别
- C/C++中产生随机数(rand,srand用法)
- 浅谈JAVA中几种循环语句的区别
- C#中的运算符及表达式(待完善)与赋值运算的区别
- 学习笔记--javascript 的<script></script>放在body和<head></head>的区别