尝试在 C 语言的硬币翻转程序中使用随机数生成器

Car*_*ria 0 c random loops coin-flipping

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

这是我的错误的输出示例

Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 1804289393
Number of tails: 846930886
Run Code Online (Sandbox Code Playgroud)

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

Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 7
Number of tails: 3
Run Code Online (Sandbox Code Playgroud)

这是程序:

#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;
} 
Run Code Online (Sandbox Code Playgroud)

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

All*_*ind 5

我建议您使用无符号整数类型numFlip。主要问题是您需要初始化numHead(原文如此)和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); // removed ! when @Fe2O3 wasn't looking :-)
    unsigned numTails = numFlip - numHeads;
    printf("Number of heads: %u\n", numHeads);
    printf("Number of tails: %u\n", numTails);
}
Run Code Online (Sandbox Code Playgroud)

和示例输出:

Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 2
Number of tails: 8
Run Code Online (Sandbox Code Playgroud)