【发布时间】:2013-03-22 12:51:19
【问题描述】:
当我第一次在rollDice() 函数中使用srand(time(NULL)) 时,它不起作用。但是当我把它放在 main 中时,它就起作用了。这是为什么?
你能告诉我其中的逻辑吗?
#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 %d\n", roll = rollDice());
if (targetPoint==roll){
printf("You win!");
status=WON;
}
else if(7==roll){
printf("You lost!");
status=LOST;
}
else
status=CONTINUE;
}
return 0;
}
【问题讨论】:
-
“不工作”是什么意思?
-
你的问题是很多,许多人在第一次尝试使用随机数接口时遇到的,并且一直是asked over and over again on Stack Overflow(搜索不都是重复的,但是其中近一半是)。
-
一开始我将 srand 放入 rollDice 时,它每次都返回 7,但是当我将它放在 main 下时,它给了我预期的不同结果。
-
在用户开始准确猜测结果之前滚动多少次? ;)