实现b进制的加法,我是先把两个数转化为十进制,然后求和在转换为b进制,可是一直出现问题,调试

#include
#include
int main()
{
int a;
char str1[40], str2[40];
while (scanf("%d%s%s", &a,str1,str2) != EOF)
{
int temp1 = 0, c1 = 1;
int length1 = strlen(str1);
printf("lenrht1=%d\n", length1);
for (int i = length1-1; i >=0; i--)
{
int x;
if (str1[i] >= 0 && str1[i] <= 9)
x = str1[i] - '0';
else
x = str1[i] - 'A' + 10;
temp1 += x*c1;
c1 *= a;
}
int temp2 = 0, c2 = 1;
int length2 = strlen(str2);
for (int i = length2 - 1; i >= 0; i--)
{
int x;
if (str2[i] >= 0 && str2[i] <= 9)
x = str2[i] - '0';
else
x = str2[i] - 'A' + 10;
temp2 += x*c2;
c2 *= a;
}
int temp = temp1 + temp2;
char ans[40];
int size = 0;
while (temp != 0)
{
int x = temp%a;
ans[size++] =(x temp /= a;
}
for (int i = size - 1; i >= 0; i--)
printf("%d\n", ans[i]);
}
return 0;
}

参考代码段
https://github.com/707wk/Senior-middle-school/blob/master/Filling%20in%20the%20gaps.c

  • if (str1[i] >= 0 && str1[i] <= 9) 应改为if (str1[i] >= '0' && str1[i] <= '9')str2同理
  • ·ans[size++] =(x temp /= a;应改为ans[size++] =x; temp /= a;`
#include <cstdio>
#include <cstring>

int main()
{
    int a;
    char str1[40], str2[40];
    freopen("1.txt", "r", stdin);
    while (scanf("%d%s%s", &a,str1,str2) != EOF)
    {
        int temp1 = 0, c1 = 1;
        int length1 = strlen(str1);
        printf("length1=%d\n", length1);
        for (int i = length1-1; i >=0; i--)
        {
            int x;
            if (str1[i] >= '0' && str1[i] <= '9')
                x = str1[i] - '0';
            else
                x = str1[i] - 'A' + 10;
            temp1 += x*c1;
            c1 *= a;
        }
        int temp2 = 0, c2 = 1;
        int length2 = strlen(str2);
        for (int i = length2 - 1; i >= 0; i--)
        {
            int x;
            if (str2[i] >= '0' && str2[i] <= '9')
                x = str2[i] - '0';
            else
                x = str2[i] - 'A' + 10;
            temp2 += x*c2;
            c2 *= a;
        }
        int temp = temp1 + temp2;
        char ans[40];
        int size = 0;
        while (temp != 0)
        {
            int x = temp%a;
            ans[size++] =x;
            temp /= a;
        }
        for (int i = size - 1; i >= 0; i--)
            printf("%d", ans[i]);
    }
    return 0;
}