C使用char[]的减法
C a subtract method with char[]
我试图实现减法方法,但发现有一些错误。
55-44是正确的555-44不正确,将返回011100-44将导致分段故障
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <sstream>
char* subtract(char *n1,char *n2){
int n1Len = strlen(n1);
int n2Len = strlen(n2);
int diff;
int max=n1Len;
char* res = (char*)malloc (max+2);
memset(res, '0', max +1);
res[max] = ' ';
int i=n1Len - 1, j = n2Len - 1, k = max;
for (; i >= 0 && j >=0; --i, --j, --k) {
if(i >= 0 && j>=0)
{
diff = (n1[i] - '0') - (n2[j] - '0');
if(diff<0)
{
int temp=n1[i-1]-'0';
temp=temp-1;
n1[i-1]=temp+'0';
diff+=10;
}
res[i]=diff+'0';
}
else
res[i]=n1[i];
}
return res;
}
int main(void) {
printf("%sn", subtract("100","44"));
}
我在GMP中写它只是为了好玩。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <gmp.h>
char* subtract(char *n1,char *n2){
mpz_t n1z, n2z;
char * res = malloc(strlen(n1) > strlen(n2) ? strlen(n1) + 1 : strlen(n2) + 1);
mpz_init_set_str(n1z, n1, 10);
mpz_init_set_str(n2z, n2, 10);
mpz_sub(n2z, n1z, n2z);
gmp_sprintf(res, "%Zd", n2z);
mpz_clear(n1z);
mpz_clear(n2z);
return res;
}
int main(void) {
printf("%sn", subtract("55","44"));
printf("%sn", subtract("555","44"));
printf("%sn", subtract("100","44"));
}
555-44不起作用的原因是您在'for'语句中测试的条件与在'if'语句中相同。如果一个字符串比另一个字符串长,则会导致循环提前退出。
100-44导致分段错误的原因是您正试图写回一个常量字符串。
您的借款逻辑也不考虑从"0"借款。
只有怎么样
int i1 = atoi(n1);
int i2 = atoi(n2);
int result = i1 - i2;
char * retval = malloc(2*strlen(n1)); // Easier than figuring out exact right size!
sprintf(retval, "%d", result);
return retval;
那不是更好吗?
相关文章:
- 使用char类型将decimal转换为string,将string转换为decimal
- 使用 char 分隔符解析C++中的字符串,但将可重复的字符保留为每个解析的子字符串 (C++ STL) 中的分隔符
- 使用 char* 存储数据和产生的错误
- 我可以以相同的方式使用 char* c 和字符串吗?
- 使用 char 数组公钥的 OpenSSL 进行 RSA 加密
- 将字符串文本分配给字符*:const_cast<字符 *> 与使用 char 数组
- 为什么 fstream.read 和 fstream.write 使用 char 而不是无符号字符?
- 使用 char 将一个字符数组分配给另一个字符数组时出现奇怪的行为
- C :如何使用char / string 2D数组接受用户的1个以上的源性
- 带有字符串(使用char数组)参数的构造函数
- 在 C++ 中使用 char* 进行初始化
- 使用 Char 数组作为多种用途的通用变量
- 使用char*时,替换了不弃用的strcpy/strcat
- 仅使用char将八分音号码转换为十进制数字
- 当使用Char Array和= Operator启动字符串时,该功能被调用
- 使用 char* 将结构传递给 C# 中的 C++ dll 函数
- 使用 char*array 存储条形图的条形图,以便我可以动态制作它并作为字符串返回
- 使用char*作为undered_map的密钥不会识别重复的密钥
- 使用 char* 增加数组 [C++]
- 错误:使用 char C++ "uninitialsed local variable 'name' used" *