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

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

问题描述

当我在第一个函数srand使用(时间(NULL)) rollDice()函数没有奏效。但是,当我把它放在主,它的工作原理。这是为什么?
你能告诉我什么逻辑?

 的#include<&stdio.h中GT;
#包括LT&;&time.h中GT;
#包括LT&;&stdlib.h中GT;INT rollDice(无效){
    收益率(1 +兰特()%6)+(1 +兰特()%6);
}
诠释主要(无效){
    INT卷;
    函数srand(时间(NULL));
    辊= rollDice();
    的printf(你滚%d个\\ n,卷);    枚举Gamestatus {赢了,输了,CONTINUE};
    枚举Gamestatus状态;    而(状态== CONTINUE){
        的printf(你又滚动:\\ n);
        的printf(你滚%d个\\ N,卷= rollDice());        如果(TARGETPOINT ==卷){
            的printf(你赢了!);
            状态= WON;
        }
        否则,如果(7 ==卷){
            的printf(你输了!);
            状态=丢失;
        }
        其他
            状态=继续;
    }
    返回0;
}


解决方案

让我们说你有几百万的书籍在随机数列行。
在你得到一个随机数,你需要选择一本书。

你有一本书,获得的随机数后,从书中读出顺序号。
改变书得到的随机数的另一序列

函数srand()选择一本书,并从一开始就开始随机数结果
兰特()读取所选书的下一个数字

如果你把函数srand()内循环,你实际上重新从同一本书开头的随机数序列。

解决方案:选择1书一次,并保持阅读人数从它直到永永远远。

在C程序中,如果不选择书,该随机数来自书#1 的,或者换句话说,在没有一个函数srand()通话,功能兰特()的行为如同函数srand(1)被调用。

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.\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;
}

解决方案

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.

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

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

Solution: select 1 book once, and keep reading numbers from it for ever and ever.

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.

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

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