本文介绍了使用递归 (c) 求数字之和 + 和 -的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在仅使用递归(不允许使用循环)的情况下找到数字、+ 和 - 序列的总和.

i need to find the sum of a sequence of numbers, + and - while using only recursion (not allowed to use loops).

我只能更改函数,仅此而已,包括函数中的指针(并且不能向其添加任何其他内容).我也不允许使用除 stdio.h 之外的任何其他库.

I can only change the function and nothing more, that includes the pointer in the function (and can't add anything else to it).I'm also not allowed to use any other library but stdio.h.

#include <stdio.h>

#define MAX_LENGTH 100

int calc_sum_string(char *s);

int main() {
    char s[MAX_LENGTH];
    scanf("%s", s);
    printf("%d", calc_sum_string(s));
    return 0;
}

int calc_sum_string(char *s) {
int sum = s[MAX_LENGTH];
if (*s == '\0'){
    return sum;
}
if (*s == '+'){
    sum = calc_sum_string(s-1)+ calc_sum_string(s+1);
}
if (*s == '-'){
    sum = calc_sum_string(s+1) - calc_sum_string(s-1);
    return sum;
}

输入:7-8+9
输出:8

推荐答案

谢谢大家,这是我的最终代码

thank you all,this is my final code

#include <stdio.h>
#define MAX_LENGTH 100

int calc_sum_string(char *s);

int main()
{
char s[MAX_LENGTH];
scanf("%s", s);
printf("%d", calc_sum_string(s));
return 0;
}

int calc_sum_string(char *s)
{
if(*s == '\0')
    return 0;
if (*s == '+'){
    return *(s+1) + calc_sum_string(s+2) - '0';
}
else if (*s == '-'){
    return -(*(s + 1) - '0') + calc_sum_string(s+2);
}
else {
    return *s - '0' + calc_sum_string(s+1);

这篇关于使用递归 (c) 求数字之和 + 和 -的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 02:45