【问题标题】:rand() is outputting the same Number for my while loop but not for my for looprand() 为我的 while 循环输出相同的数字,但不是为我的 for 循环
【发布时间】:2020-03-07 01:36:39
【问题描述】:

我正在为随机掷骰子制作此代码,我想获得一个随机数,直到我在骰子上得到三个 6。出于某种原因,这会为所有运行产生相同的数字,但在我的 for 循环中它可以工作。我可以得到一些帮助来让它工作吗?

有问题的讨厌的 While 循环:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int Ran(int max) {
return (rand() % max)+ 1;
}

int main(){

    int max = 6;
    int nsuc = 0, ncount = 0;
    int matt = 40;
    srand((unsigned) time(0));

    for(int i = 1; i <= 20; i++){
        while(!(nsuc >= 3)){
            int nr = Ran(max);
            if(nr < matt){
                ncount++;
                if(nr == 6){
                    nsuc++;
                }
            }
        }
        printf("Number of rolls until 3 6's = %d\n", ncount);
    }
}

清理了 for 循环,使其现在更易于阅读:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


void Shuffle() {
srand((unsigned) time(NULL));
}

int Ran(int max) {
return (rand() % max)+ 1;
}

void binomial(int run, int max, int btrials, int *array, int scount){

    for(int j = 1; j<=run; j++){
        for (int i=1;i<=btrials;i++){
            int r = Ran(max);
            if(r == 6){
            scount++;
            }
        printf("Trial %i, roll = %d\n",i , r);
        }
        array[j-1] = scount;
        scount = 0;
        printf("\nEnd of Run %d\n\n",j);
    }

}

int main(){

    int Runs;
    printf("How many runs do you want to do? > ");
    scanf("%d", &Runs);
    printf("\n");

    int bdist[20];
    int distcount = 0;
    int max = 6;
    int btrials = 20;
    int suc[Runs+1];
    int scount = 0;



    Shuffle();
    binomial(Runs, max, btrials, suc, scount);

    printf("All counts of succesful 6 rolls.\n");

    /*
    for(int z = 1; z<=Runs; z++){
        printf("Run %d has %d 6's\n", z, suc[z-1]);
    }
    */

    for(int k = 0; k<=btrials; k++){
        for(int j = 1; j<=Runs; j++){
            if(suc[j-1] == k){
                distcount++;
            }     
        }
        bdist[k] = distcount;
        distcount = 0;
    }

    for(int t = 0; t<=btrials; t++){
        printf("Number of runs with %d 6s = %d\n", t, bdist[t]);
    }

    return 0;

}

【问题讨论】:

    标签: c random while-loop


    【解决方案1】:

    在带有 while 循环的第一个版本中,您永远不会重置 nsucncount。第一次通过后,它们仍然具有上一个循环的值,因此您得到相同的输出。

    【讨论】:

    • 是的,你明白了,我非常专注于 rand(),我只是忘了做一些如此基本的事情。谢谢你的帮助,我想我今天应该从编码中休息一下。
    【解决方案2】:

    不是与问题严格相关的答案,而是我注意到的。

    如果我记得,不建议使用 (rand % max)+ 1 成语生成范围随机数。

    One.

    Two

    【讨论】:

    • 正如您所说,这不能回答问题。这将是一个公平的评论。请等到您获得更多积分 - 请注意,将 cmets 作为答案发布将无济于事您到达那里。
    • 会做,只是想做我的一部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 2023-04-10
    • 1970-01-01
    • 2012-11-07
    • 2018-04-20
    • 1970-01-01
    • 2018-05-24
    相关资源
    最近更新 更多