finding the sum of numbers, + and - using recursio

2019-09-27 16:59发布

问题:

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

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

input: 7-8+9
output: 8

回答1:

#include <stdio.h>

#define MAX_LENGTH 100

//Stringification
#define S_(n) #n
#define S(n) S_(n)

int calc_sum_string(char *s);

int main(void){
    char s[MAX_LENGTH+1];

    scanf("%" S(MAX_LENGTH) "s", s);
    printf("%d", calc_sum_string(s));

    return 0;
}

int calc_sum_string(char *s){
//It is assumed that there is no space character in the character string.
//The string is not changed within this function.
    int n, len;

    if (*s == '\0' || 1 != sscanf(s, "%d%n", &n, &len)){
        return 0;
    }
    return n + calc_sum_string(s + len);
}


回答2:

Your present code has several problems. The ones you need to address first include:

  • You never use any of the digits to create a base value: the 7, 8, and 9 are never interpreted as numbers. Your only base case returns 0, so that's the only result your code is capable of reaching.
  • Your + and - cases have identical code in them: there's no difference in the processing.
  • You reference character positions s-1 and s-3 in your recursive calls. These move you backwards into memory that's not part of your string. You need to move toward the end of the string.

Fix those items. If you still have problems, please give us a proper posting of your remaining problems, and we'll help you get over the hump.



回答3:

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 recursion sum