帮我用c++风格写一段高精度加法运算函数
时间: 2024-05-03 18:20:04 浏览: 7
好的,以下是用 C 语言风格编写的高精度加法运算函数:
```c
#include <stdio.h>
#include <string.h>
#define MAX_DIGIT 1000
void reverse(char* s, int len) {
char t;
for (int i = 0; i < len / 2; ++i) {
t = s[i];
s[i] = s[len - i - 1];
s[len - i - 1] = t;
}
}
void add(char* a, char* b, char* res, int len_a, int len_b) {
int carry = 0;
int len_res = 0;
while (len_a > 0 || len_b > 0) {
int x = (len_a > 0) ? a[len_a - 1] - '0' : 0;
int y = (len_b > 0) ? b[len_b - 1] - '0' : 0;
int sum = x + y + carry;
res[len_res++] = sum % 10 + '0';
carry = sum / 10;
len_a--;
len_b--;
}
if (carry > 0) {
res[len_res++] = carry + '0';
}
res[len_res] = '\0';
reverse(res, len_res);
}
int main() {
char a[MAX_DIGIT], b[MAX_DIGIT];
fgets(a, MAX_DIGIT, stdin);
fgets(b, MAX_DIGIT, stdin);
int len_a = strlen(a) - 1; // 去掉换行符
int len_b = strlen(b) - 1;
char res[MAX_DIGIT];
add(a, b, res, len_a, len_b);
printf("%s\n", res);
return 0;
}
```
这个函数会通过标准输入读入两个字符串,分别代表两个加数,然后计算它们的和,并将结果打印到标准输出。注意,这个函数只能用于非负整数的加法运算。