首页 > 解决方案 > 在C中递归地在1-1000范围内的整数的三元系数

问题描述

我必须找到给定数字的三元系数。

例如,如果给定的数字是 29,则所需的输出应该是 -1101。更多示例:7 表示 1-11,10 表示 101。

我尝试使用字符数组递归地解决问题,但我是 C 新手,因此存在我无法解决的运行时错误。代码在这里给出 -

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

char *coefficient();

int main()
{
    int n;
    printf("Input a number between 1 and 1000: ");
    scanf("%d",&n);
    if(n<1 || n>1000){
        printf("Invalid Input. Please try again");
        scanf("%d",&n);
    }

    //Calculating the size of the char array
    int dummyN = n;
    int count = 1;
    while(dummyN>1){
        count++;
        dummyN/=3;
    }
    char c[count];

    printf("Coefficient sequence %s\n",coefficient(n,c));
    return 0;
}


char *coefficient(int n, char *c){
    if (n>1){
        int rem = n%3;
        n = n/3;
        char finrem;
        if(rem==2){
            rem = -1;
            n++;
        }
        else finrem = rem +'0';
        strcat(c, finrem);
        c=coefficient(n,c);
    }
    else if (n==1){
        char i = '1';
        strcat(c, i);
    }
    return c;
}

标签: arrayscrecursionruntime-errorternary

解决方案


推荐阅读