在 rollDice 函数中调用 srand(time(NULL)) 时出现的问题 [英] Problems when calling srand(time(NULL)) inside rollDice function

查看:24
本文介绍了在 rollDice 函数中调用 srand(time(NULL)) 时出现的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我首先在 rollDice() 函数中使用 srand(time(NULL)) 时,它不起作用.但是当我把它放在 main 中时,它就起作用了.这是为什么?你能告诉我逻辑吗?

When I used at first srand(time(NULL)) in rollDice() function it did not work. But when I put it in main, it works. Why is that? Can you tell me the logic?

#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.
", roll);

    enum Gamestatus {WON,LOST,CONTINUE};
    enum Gamestatus status;

    while(status==CONTINUE){
        printf("You are rolling again: 
");
        printf("You rolled %d
", roll = rollDice());

        if (targetPoint==roll){
            printf("You win!");
            status=WON;
        }
        else if(7==roll){
            printf("You lost!");
            status=LOST;
        }
        else
            status=CONTINUE;
    }
    return 0;
}

推荐答案

假设您有数百万本书,其中包含一排排随机数字.在获得随机数之前,您需要选择一本书.

Let's say you have millions of books with rows upon rows of random numbers. Before you get a random number you need to select a book.

拥有一本书后,要获得随机数,请从书中按顺序读取数字.换书会得到另一个随机数序列.
切换到同一本书会从书中的第一个数字重新开始序列.

After you have a book, to get random numbers, read numbers sequentially from the book. Changing the book gets another sequence of random numbers.
Changing to the same book restarts the sequence form the first number in the book.

srand() 选择一本书并从头开始随机数
rand() 从选中的书中读取下一个数字

srand() chooses a book and starts random numbers from the beginning
rand() reads the next number from the selected book

如果将 srand() 放入循环中,则实际上是从同一本书的开头重新开始随机数序列.

If you put srand() inside the loop, you are effectively restarting the random number sequence from the beginning of the same book.

解决方案:选择 1 本书一次,并永远读取其中的数字.

在 C 程序中,如果不选择一本书",随机数来自第一本书,或者换句话说,在没有 srand() 调用,函数 rand() 的行为就像 srand(1) 已被调用一样.

In a C program, if you don't "select a book", the random numbers come from book #1 or, in other words, in the absence of a srand() call, the function rand() behaves as if srand(1) has been called.

这篇关于在 rollDice 函数中调用 srand(time(NULL)) 时出现的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆