繁体   English   中英

尝试在 C 中的抛硬币程序中使用随机数生成器

[英]Trying to use random number generator in a coin flip program in C

你好我正在尝试创建一个程序,它根据用户输入的硬币翻转次数计算硬币翻转模拟器中正面和反面的数量。 这个问题是,当我试图计算正面和反面的数量然后递增它们时,它只给我一个随机数,而不是在给定的翻转范围内。

这是我的错误示例 output

Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 1804289393
Number of tails: 846930886

相反,我希望它像这样计算:

Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 7
Number of tails: 3

这是程序:

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

int main(void) {
  printf("Coin Flip Simulator\n");
  printf("How many times do you want to flip the coin? ");
  int numFlip = getdouble();
  if(numFlip == 0 || numFlip < 0) {
    printf("Error: Please enter an integer greater than or equal to 1.\n");
  }
  int i = 0;
  int numHead = rand();
  int numTails = rand();
  for (i = 0; i < numFlip; i++) {
    
    if(numFlip%2 == 0) {
      numHead++;
    }
    else {
      numTails++;
    }
  }
  printf("Number of heads: %d\n", numHead);
  printf("Number of tails: %d\n", numTails);
  
  return 0;
} 

感谢您的建议,这是我第一次尝试使用随机数生成器。

我建议您为numFlip使用无符号的 integer 类型。 主要问题是您需要初始化numHead (sic) 和numTails 您想使用srand()为随机数生成种子,否则结果是确定性的。 因为你只有两个选项,所以只记录正面的数量并在事后确定反面:

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

int main() {
    srand(time(0));
    printf("Coin Flip Simulator\n");
    printf("How many times do you want to flip the coin? ");
    unsigned numFlip;
    if(scanf("%u", &numFlip) != 1) {
        printf("numFlip failed\n");
        return 1;
    }
    unsigned numHeads = 0;
    for(unsigned i = 0; i < numFlip; i++)
        numHeads += !(rand() % 2); // remove ! when @Fe2O3 isn't looking
    unsigned numTails = numFlip - numHeads;
    printf("Number of heads: %u\n", numHeads);
    printf("Number of tails: %u\n", numTails);
}

和示例 output:

Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 2
Number of tails: 8

暂无
暂无

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

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