gpt4 book ai didi

c - 在 C 中添加由随机数生成器生成的数字

转载 作者:太空宇宙 更新时间:2023-11-04 04:35:08 25 4
gpt4 key购买 nike

在我提出问题之前,我想指出我确实已经在寻找答案,但我没有找到我要找的东西。请记住,我是编程方面的初学者,所以请不要以为我什么都知道。对了,正题。我的问题是:如何将随机数生成器创建的数字相加?我遇到的困难是每次运行程序时随机生成的数字的数量可能不同。更清楚地说,随机生成的数字的数量取决于用户的输入,例如,如果输入是 9,程序将生成 9 个随机数。这让我很难想出如何将随机数加在一起并显示它们的想法。这是我程序的源代码。我认为重要的是要提到每次运行程序时随机数都会发生变化,这就是我希望它们成为的样子(我使用 srand() 和 rand() )。另外,我目前遇到的问题是程序将最后随机生成的数字加倍,而不是将它们加在一起。

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

int main(void)
{
int input;
scanf("%d", &input);
int i;
int roll;
int turn_total;
time_t t;
int sum;

srand((unsigned) time(&t)); // the seed for the random number generator based on the current time

for( i = 0; i < input; i++)
{
roll = (rand() % 6 + 1); // random number generator
sum = roll+roll; // only dubbling the last roll for some reason = /
printf("You Rolled : %d\n", roll);
}

printf("The Total Turn Score is : %d", sum);
}

如有任何帮助、想法或线索,我们将不胜感激。

最佳答案

你需要先初始化 sum 并且你没有正确添加。

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

int main(void)
{
int input;
scanf("%d", &input);
int i;
int roll;
time_t t;
int sum = 0;

srand((unsigned) time(&t)); // the seed for the random number generator based on the current time


for( i = 0; i < input; i++)
{
roll = (rand() % 6 + 1); // random number generator
sum += roll; // only dubbling the last roll for some reason = /
printf("You Rolled : %d\n", roll);
}

printf("The Total Turn Score is : %d", sum);

}

关于c - 在 C 中添加由随机数生成器生成的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31425558/

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