二进制数之和(使用C样式字符串)

Sum Of Binary Numbers (using C Style Strings)

本文关键字:样式 字符串 使用 二进制数      更新时间:2023-10-16

我正在编写一个程序,将命令行输入(argv,argc(中的两个二进制数相加。它也是左对齐的。

例如:$a.out 0 1返回1,$a.out 10 1返回11等

我用一个函数来做加法,我知道100%的问题都在我的函数中,但我不知道我做错了什么。当我把两个进位为"0"的二进制数相加时,它不会在和中打印"1"。我还有一个问题,有些金额是反向打印的,而不是其他的。如果有人能给我指出我做错了什么,我将不胜感激

错误总和的示例:

$a.out 10 10
00      // should be "100"
$a.out 11 11
01      // should be "110"
$a.out 100 100
000     // should be "1000"
$a.out 110000 1
100011 // should be "110001"

我的功能:

bool add (const char aug[], const char add[], char sum[])
//aug is the first command line binary number (argv[1]), add is the second (argv[2])
{
char carry = '0';
int ag = strlen(augend) - 1;
int ad = strlen(addend) - 1;
int max = ((ag > ad)? ag : ad);
for (int i = 0; i <= max; ag--, ad--, i++)
{
char augDigit = (ag < 0)? '0' : augend[ag];
char addDigit = (ad < 0)? '0' : addend[ad];
switch (augDigit + addDigit + carry)
{
case '0' + '0' + '0':
sum[i] = '0';
carry = '0';
break;
case '1' + '0' + '0':
sum[i] = '1';
carry = '0';
break;
case '1' + '1' + '0':
sum[i] = '0';
carry = '1';
break;
case '1' + '1' + '1':
sum[i] = '1';
carry = '1';
break;
}
}    
return true; 
// returns true if the sum is less than 36 digits but I'll deal with         
// that once i fix this issue
}

两个原因:第一个原因是以相反的顺序存储结果,第二个原因是没有计算最后一次进位。如果最后一个和执行了,则必须在结果中附加另一个'1'