[英]Sum Of Binary Numbers (using C Style Strings)
我正在研究一个程序,从命令行输入(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'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.