在rollDice函数内调用srand(time(NULL))时出现问题
发布时间:2020-12-16 10:23:58 所属栏目:百科 来源:网络整理
导读:当我在rollDice()函数中使用第一个srand(time(NULL))时它不起作用.但是当我把它放在主要部分时,它可以工作.这是为什么? 你能告诉我逻辑吗? #include stdio.h#include time.h#include stdlib.hint rollDice(void) { return (1+rand()%6) + (1+rand()%6);}in
当我在rollDice()函数中使用第一个srand(time(NULL))时它不起作用.但是当我把它放在主要部分时,它可以工作.这是为什么?
你能告诉我逻辑吗? #include <stdio.h> #include <time.h> #include <stdlib.h> int rollDice(void) { return (1+rand()%6) + (1+rand()%6); } int main(void) { int roll; srand(time(NULL)); roll = rollDice(); printf("You rolled %d.n",roll); enum Gamestatus {WON,LOST,CONTINUE}; enum Gamestatus status; while(status==CONTINUE){ printf("You are rolling again: n"); printf("You rolled %dn",roll = rollDice()); if (targetPoint==roll){ printf("You win!"); status=WON; } else if(7==roll){ printf("You lost!"); status=LOST; } else status=CONTINUE; } return 0; } 解决方法
假设你有数百万本随机数字行的书籍.
在获得随机数之前,您需要选择一本书. 拿到书后,要获得随机数,请从书中依次读取数字. srand()选择一本书并从头开始随机数 如果将srand()放在循环中,则实际上是从同一本书的开头重新启动随机数序列. 解决方案:选择一本书一次,并始终从中读取数字. 在C程序中,如果你不“选择一本书”,随机数来自书#1,换句话说,在没有srand()调用的情况下,函数rand()的行为就像srand一样( 1)被称为. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |