gpt4 book ai didi

c - 如何从一个函数中检索一个数字以便在另一个函数中使用它?

转载 作者:行者123 更新时间:2023-11-30 18:49:34 25 4
gpt4 key购买 nike

(C 代码)每个骰子都有自己的函数,我想要一个函数来对每个骰子的结果求和。但是如何从第一个和第二个函数中检索值并将它们放入第三个函数中求和呢?见下文

int roll_die1(void)
{
int random_int;
srand((unsigned int)time(NULL));
random_int = rand() % (6) + 1;
printf("The outcome of your first Roll is: %d.\n", random_int);

return random_int;
}

int roll_die2(void)
{
int random_int2;
srand((unsigned int)time(NULL));
random_int2 = rand() % (6) + 1;
printf("The outcome of your second Roll is: %d.\n", random_int2);

return random_int2;

}

int calculate_sum_dice(int die1_value, int die2_value)
{
int sum = die1_value + die2_value;
return sum;
}

现在我不能只将前两个函数调用到第三个函数中,因为它会重复这些函数中的所有步骤,那么我该怎么做?

编辑:在我的 main.c 中,获取我所做的总和

roll1 = roll_die1();
roll2 = roll_die2();
sum = calculate_sum_dice(roll1, roll2);

最佳答案

只需允许 calculate_sum_dice() 检索 roll_die1()roll_die2() 的结果并返回总和。他们不需要为 calculate_sum_dice() 包含任何函数参数。您也可以在 main() 中调用一次 srand() ,因为它只是为 rand() 设置一个种子,所以它是多次调用它是没有意义的。看看srand(): why call it just once? ,正如@Jonathan Leffler 在评论中指出的那样。

您的代码应如下所示:

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

int roll_die1(void) {
int random_int;
random_int = rand() % (6) + 1;
printf("The outcome of your first Roll is: %d.\n", random_int);

return random_int;
}

int roll_die2(void) {
int random_int2;
random_int2 = rand() % (6) + 1;
printf("The outcome of your second Roll is: %d.\n", random_int2);

return random_int2;

}

int calculate_sum_dice(void) {
int sum = roll_die1() + roll_die2();
return sum;
}

int main(void) {
srand((unsigned int)time(NULL));

int sum = calculate_sum_dice();

printf("Dice sum = %d\n", sum);

return 0;
}

关于c - 如何从一个函数中检索一个数字以便在另一个函数中使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42451797/

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