#include<stdio.h> #include<string.h> struct bign { int d[1000]; int len; bign() { //构造函数(函数名和结构体相同, 无返回值) memset(d, 0, sizeof(d)); //头文件<string.h> len = 0; } }; bign change(char str[]) { //字符串倒着赋给d[]数组 bign a; a.len = strlen(str); for (int i = 0; i < a.len; i++) { a.d[i] = str[a.len - i - 1] - ‘0‘; //逆着赋值 } return a; } int compare(bign a, bign b) { //比较两个bign变量的大小 if (a.len > b.len) return 1; else if (a.len < b.len) return -1; else { for (int i = a.len - 1; i >= 0; i--) { if (a.d[i] > b.d[i]) return 1; else if (a.d[i] < b.d[i]) return -1; } return 0; } } bign add(bign a, bign b) { //高精度加法 bign c; int carry = 0; //进位 for (int i = 0; i < a.len || i < b.len; i++) { int temp = a.d[i] + b.d[i] + carry; c.d[c.len++] = temp % 10; carry = temp / 10; } if (carry != 0) { c.d[c.len++] = carry; } return c; } bign sub(bign a, bign b) { //高精度减法(使用前需要比较两个数的大小, 如果被减数小于减数, 需要交换两个变量,然后输出负号, 再使用sub函数) bign c; for (int i = 0; i < a.len || i < b.len; i++) { if (a.d[i] < b.d[i]) { a.d[i + 1]--; a.d[i] += 10; } c.d[c.len++] = a.d[i] - b.d[i]; } while (c.len - 1 >= 1 && c.d[c.len - 1] == 0) { c.len--; } return c; } bign multi(bign a, int b) { //高精度与低精度的乘法 bign c; int carry = 0; for (int i = 0; i < a.len; i++) { int temp = a.d[i] * b + carry; c.d[a.len++] = temp % 10; carry = temp / 10; } while (carry != 0) { c.d[c.len++] = carry % 10; carry /= 10; } return c; } bign divide(bign a, int b, int &r) { bign c; c.len = a.len; //被除数的每一位和商的每一位是一一对应的。因此先令长度相等 for (int i = a.len - 1; i >= 0; i--) { r = r * 10 + a.d[i]; if (r < b) c.d[i] = 0; else { c.d[i] = r / b; //商 r = r % b; //获得的余数 } } while (c.len - 1 >= 1 && c.d[c.len - 1] == 0) { c.len--; } return c; } bign divide(bign a, int b, int &r) { //高精度除法与低精度除法的运算 // r为余数 bign c; c.len = a.len; for (int i = a.len - 1; i >= 0; i--) { r = r * 10 + a.d[i]; if (r < b) c.d[i] = 0; else { c.d[i] = r / b; r = r % b; } } while (c.len - 1 >= 1 && c.d[c.len - 1] == 0) { c.len--; } return c; } int main() { char str1[1000], str2[1000]; scanf("%s%s", str1, str2); bign a = change(str1); bign b = change(str2); bign c = add(a, b); for (int i = c.len - 1; i >= 0; --i) { printf("%d", c.d[i]); } return 0; }
原文地址:https://www.cnblogs.com/Yaxadu/p/9189309.html
时间: 2024-11-06 07:15:31