二进制数之和(使用C样式字符串)
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'
。
相关文章:
- 二进制数之和(使用C样式字符串)
- 从 C 样式字符串中删除子字符串 "in place" 在C++代码中
- 比较 std::string 和 C 样式字符串文字
- 为什么打印 c 样式字符串的'address of index n'会导致子字符串的输出
- 为什么 C 样式字符串的工作空指针检查不?
- C++ - 创建具有相同字符的特定大小的以 null 结尾的 c 样式字符串的更好方法
- C++ 一个自定义类字符串,将其分配给 C 样式字符串
- C++ C 样式字符串/字符数组的大小 - 优化
- 此代码如何启动索引为 1 的 C 样式字符串
- 在C++中标记化"Braced Initializer List"样式字符串(使用 Boost?
- 将 C 样式字符串复制到免费存储上分配的内存中
- std::对 C 样式字符串进行排序,而不复制字符串
- 异常和 C 样式字符串
- 重载分辨率 C 样式字符串
- 如何在C++中有条件地设置 C 样式字符串?
- 转换为C样式字符串
- 是否可以同时使用 C++11 ABI _and_ cxx11 样式和旧样式字符串
- 从scanf读取C样式字符串时出现分段错误
- 如何比较 C 样式字符串
- 我的 C 样式字符串中的最后字符是 I 时的奇数值