gpt4 book ai didi

c - C 中通过函数实现随机数(初级程序员)

转载 作者:行者123 更新时间:2023-11-30 19:10:04 24 4
gpt4 key购买 nike

我创建了一个简单的游戏,让用户猜测 1 到 10 之间的随机数。它运行良好,然后我将其调整为一个函数,该函数采用 2 个参数(一个高值和一个低值)来生成随机数数字。当函数应该返回随机数时,通过函数执行此操作始终返回作为参数输入的最大数字的值。这是我的代码:

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

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

基本上,我正在尝试编写一个可以在其他程序中重用的函数来生成 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)。预先感谢您提供的任何和所有帮助,我希望这篇文章能让您满意。

最佳答案

 rand()%maxNum + minNum;

rand ()将生成 0 之间的数字和RAND_MAX .

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

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

  • 要获得 MIN 和 MAX 之间的正确随机数,最好遵循此公式:

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

关于c - C 中通过函数实现随机数(初级程序员),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41906874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com