【问题标题】:How do I generate different random numbers in a loop in C?如何在 C 中的循环中生成不同的随机数?
【发布时间】:2014-11-27 01:56:08
【问题描述】:

我正在尝试制作一个使用 6 个骰子的骰子游戏。我可以每卷生成一个随机数,问题是我一直得到相同的数字(如果生成的数字是 1,每个骰子都是 1)。有没有办法让每个骰子得到的数字不一样?

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

int main() {

    int i;
    int diceRoll;
    srand(time(NULL));
    int r = (rand()%6)+1;

    printf("\t\t\t Welcome to Dice Game!\n");

    for( i = 0; i < 6; i ++){
        diceRoll= r;
        printf(" %d \n", diceRoll);
    }

 return 0;

}

【问题讨论】:

    标签: c loops random


    【解决方案1】:

    只需将其放入 for 循环中即可:

    r = (rand()%6)+1;
    

    并像这样在它之外声明r

    int r;
    

    OR你不使用 r,程序看起来像这样

    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <time.h>
    
    int main() {
    
        int count, diceRoll;
        srand(time(NULL));
    
        printf("\t\t\t Welcome to Dice Game!\n");
    
        for(count = 0; count < 6; count ++){
            diceRoll = (rand()%6)+1;
            printf(" %d \n", diceRoll);
        }
    
        return 0;
    
    }
    

    【讨论】:

    • 我想我定义 r 有点太早了。感谢您的帮助!
    【解决方案2】:

    你考虑过

    for( i = 0; i < 6; i ++){
        diceRoll= (rand()%6) + 1;
        printf(" %d \n", diceRoll);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-23
      • 1970-01-01
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      相关资源
      最近更新 更多