尝试使用随机数发生器在一个硬币投掷程序在C

n7taea2i  于 2023-02-03  发布在  其他
关注(0)|答案(1)|浏览(127)

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

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;
}

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

kmpatx3s

kmpatx3s1#

我建议你对numFlip使用unsigned 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);
}

和示例输出:

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

相关问题