gpt4 book ai didi

c - 为什么我不能在 C 中返回递归函数的最后一个值?

转载 作者:行者123 更新时间:2023-12-04 23:53:58 24 4
gpt4 key购买 nike

我一直在尝试构建一个计算最大值的递归函数,但即使我在函数中打印时可以看到总值,我也无法将该值返回给主函数。你能告诉我我哪里做错了吗?感谢您的帮助!

注意:关于我一直在尝试构建的内容的更多解释是:用户定义一个对象,只要用户不给出价格,我就会一直问这个对象是什么..

小例子:

Define the object:  
Car
What is Car?:
4*Wheel+1*Frame
What is Wheel?:
2*Rim
What is Rim?
5.0
What is Frame?:
10.0
Total is : 50.0

当前代码:

#include <stdio.h>
#include <stdlib.h>
#define INPUT_SIZE 101

void delete_space(char arr[])
{
int a, i, j, len;
for(a = 0; a < INPUT_SIZE; a++)
{
for(i = 0; i < INPUT_SIZE; i++)
{
if(arr[i] == ' ')
{
for(j = i; j < INPUT_SIZE; j++)
{
arr[j] = arr[j + 1];
}
}
}
}
}


double result(char input[], double coeff, double total)
{
/* if the input is number, num_of_obj is 0, if the input is object, num_or_obj is more than 0.
*/
int i, k = 1, num_of_obj = 0;
char temp_input[INPUT_SIZE];
char temp_input_1[INPUT_SIZE];
char x;
int* p;
double value;
p = (int*)calloc(1, sizeof(int));
p[0] = 0;
printf("What is %s:?\n", input);
scanf("%[^\n]s", temp_input);
getchar();
delete_space(temp_input);
for(i = 0; i < INPUT_SIZE; i++)
{
if(temp_input[i] == '*')
{
num_of_obj++;
}
}
if(num_of_obj == 0) // if the input is number.
{
sscanf(temp_input, "%lf", &value);
total = total + coeff * value;
printf("total : %lf", total);
return total;
}
if(num_of_obj > 0)
{
for(i = 0; i < INPUT_SIZE; i++)
{
if(temp_input[i] == '+')
{
p = (int*)realloc(p, (k + 1) * sizeof(int));
p[k] = i + 1;
k++;
}
}
for(i = 0; i < k; i++)
{
sscanf(&temp_input[p[i]], "%lf%c%[^+]s", &coeff, &x, temp_input_1);
result(temp_input_1, coeff, total);
}
}
printf("test");
return total;
}

int main()
{
double total = 0;
char input[INPUT_SIZE];
printf("Define the object :\n");
scanf("%[^\n]s", input);
getchar();
delete_space(input);
printf("total : %.2lf", result(input, 0, 0));
return 0;
}

最佳答案

我认为主要问题是递归调用:result(temp_input_1, coeff, total);,它忽略了返回的结果。

两种可能的解决方案:(1) 在 result 中进行聚合或 (2) 尾递归。我不确定这种情况是否适合尾递归(或者这里有什么好处)。考虑从 result 原型(prototype)中删除“总计”,并在循环中进行聚合(在“组件”上)。

double result(char input[], double coeff) {
double total ;

...
for(i = 0; i < k; i++)
{
sscanf(&temp_input[p[i]], "%lf%c%[^+]s", &coeff, &x, temp_input_1);
total += result(temp_input_1, coeff, total);
}

旁注:考虑同时删除“delete_space”功能。我相信它不会对 fix 字符串进行属性处理。在 scanf 调用中跳过空格要容易得多。

关于c - 为什么我不能在 C 中返回递归函数的最后一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59186791/

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