问题描述
我必须找到给定数字的三进制系数。
例如,如果给定的数字为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;
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)