繁体   English   中英

rand() 为我的 while 循环输出相同的数字但不是我的 for 循环

[英]rand() is outputting the same Number for my while loop but not for my for loop

我正在为随机掷骰子制作此代码,我想获得一个随机数,直到骰子上出现三个 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;

}

在第一个版本中,您永远不会使用 while 循环重置nsucncount 在第一次 thru 之后,它们仍然具有前一个循环中的值,因此您可以获得相同的输出。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM