C中的随机数通过函数(初级程序员)

时间:2017-01-28 06:04:14

标签: c function random

我创建了一个简单的游戏,让用户猜测一个从1到10的随机数。它工作正常,然后我调整到我做了一个函数,其中有两个参数,一个高和低的值,生成一个随机的数。通过该函数执行此操作始终返回作为参数输入的最大数字的值,它应返回一个随机数。这是我的代码:

#include "stdio.h"
#include "stdlib.h"
#include "time.h"

int main(void) {

  int storedNum, low, high, userGuess;

  printf("Welcome to my random numbers game! You will choose a lower number and a maximum number and me, the computer, will choose a random number between those two values for you to guess.\n\nFirst, choose the lowest value");
  scanf("%d", &low);
  printf("Now, choose the highest value");
  scanf("%d", &high);

  storedNum = randomNumbers(low, high);
  printf("We have guessed a number between %d and %d. Guess our number!: ", low, high);
  scanf("%d", &userGuess);

  while (userGuess != storedNum){
    if(userGuess < storedNum){
      printf("higher!: ");
      scanf("%d", &userGuess);
    }
    else{
      printf("Lower!: ");
      scanf("%d", &userGuess);
    }
  }

  printf("You are correct the number was %d!", storedNum);
  return 0;
}

int randomNumbers(int maxNum, int minNum){
  int number;
  srand(time(NULL));
  number = rand()%maxNum + minNum;
  return number;
}

只要我在main方法中生成随机数,代码就可以正常工作,但每当我通过函数使用它时,我总会获得相同的返回值。我认为问题在于函数内部的种子,但我并不完全确定。即使这是问题,我也不确定如何解决这个问题并使我的代码正常工作。

基本上,我正在尝试编写一个函数,我可以在其他程序中重用它来生成x和y之间的随机数。

这是一些示例输出:

Welcome to my random numbers game! You will choose a lower number and a maximum number and me, the computer, will choose a random number between those two values for you to guess.

First, choose the lowest value 1
Now, choose the highest value 10
We have guessed a number between 1 and 10. Guess our number!:  5
higher!:  8
higher!:  9
higher!:  10
You are correct the number was 10! 

无论我输入什么数字,它总是返回最大值(在这种情况下为10)。提前感谢任何和所有的帮助,我希望这篇文章能找到你。

2 个答案:

答案 0 :(得分:3)

 rand()%maxNum + minNum;

rand ()会在0RAND_MAX之间生成一个数字。

rand%maxNum将是一个数字<= min(rand(),maxNum-1)

所以你得到的数字是<=min(rand(),maxNum-1) + minNum,可能超过maxNum

  • 要在MIN和MAX之间获得正确的随机数,最好坚持这个公式:

    (rand() % (MAX - MIN + 1)) + MIN;

答案 1 :(得分:-2)

rand()非常直接