问题描述
- 实现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=%dn", 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("%dn", ans[i]);
}
return 0;
}
解决方案
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=%dn", 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;
}
解决方案二:
参考代码段
https://github.com/707wk/Senior-middle-school/blob/master/Filling%20in%20the%20gaps.c
时间: 2024-09-19 09:58:53