#include <stdio.h>\n#include <string.h>\n\n#define MAX_DIGITS 50\n\nvoid reverse(char *str) {\n int length = strlen(str);\n for (int i = 0; i < length / 2; i++) {\n char temp = str[i];\n str[i] = str[length - i - 1];\n str[length - i - 1] = temp;\n }\n}\n\nvoid add(char *a, char *b, char *result) {\n int carry = 0;\n int i = 0;\n while (a[i] != '\0' || b[i] != '\0') {\n int sum = carry;\n if (a[i] != '\0') {\n sum += a[i] - '0';\n }\n if (b[i] != '\0') {\n sum += b[i] - '0';\n }\n result[i] = sum % 10 + '0';\n carry = sum / 10;\n i++;\n }\n if (carry > 0) {\n result[i] = carry + '0';\n i++;\n }\n result[i] = '\0';\n reverse(result);\n}\n\nvoid subtract(char *a, char *b, char *result) {\n int borrow = 0;\n int i = 0;\n while (a[i] != '\0' || b[i] != '\0') {\n int diff = borrow;\n if (a[i] != '\0') {\n diff += a[i] - '0';\n }\n if (b[i] != '\0') {\n diff -= b[i] - '0';\n }\n if (diff < 0) {\n borrow = -1;\n diff += 10;\n } else {\n borrow = 0;\n }\n result[i] = diff + '0';\n i++;\n }\n result[i] = '\0';\n reverse(result);\n}\n\nvoid multiply(char *a, char *b, char *result) {\n int lengthA = strlen(a);\n int lengthB = strlen(b);\n int lengthResult = lengthA + lengthB;\n\n int carry = 0;\n for (int i = lengthB - 1; i >= 0; i--) {\n int j;\n for (j = lengthA - 1; j >= 0; j--) {\n int product = (a[j] - '0') * (b[i] - '0') + carry + (result[lengthResult - 1 - (lengthB - 1 - i) - (lengthA - 1 - j)] - '0');\n result[lengthResult - 1 - (lengthB - 1 - i) - (lengthA - 1 - j)] = product % 10 + '0';\n carry = product / 10;\n }\n result[lengthResult - 1 - (lengthB - 1 - i) - (lengthA - 1 - j)] = carry + '0';\n carry = 0;\n }\n result[lengthResult] = '\0';\n reverse(result);\n}\n\nvoid divide(char *a, char *b, char *result) {\n int lengthA = strlen(a);\n int lengthB = strlen(b);\n int lengthResult = lengthA - lengthB + 1;\n\n char tempA[MAX_DIGITS];\n strcpy(tempA, a);\n\n for (int i = 0; i < lengthResult; i++) {\n int quotient = 0;\n while (tempA[i] >= b[0]) {\n subtract(tempA + i, b, tempA + i);\n quotient++;\n }\n result[i] = quotient + '0';\n }\n result[lengthResult] = '\0';\n}\n\nint main() {\n char a[MAX_DIGITS];\n char b[MAX_DIGITS];\n char result[MAX_DIGITS];\n\n printf("Enter the first number: ");\n scanf("%s", a);\n\n printf("Enter the second number: ");\n scanf("%s", b);\n\n add(a, b, result);\n printf("Addition: %s + %s = %s\n", a, b, result);\n\n subtract(a, b, result);\n printf("Subtraction: %s - %s = %s\n", a, b, result);\n\n multiply(a, b, result);\n printf("Multiplication: %s * %s = %s\n", a, b, result);\n\n divide(a, b, result);\n printf("Division: %s / %s = %s\n", a, b, result);\n\n return 0;\n

C语言实现大整数加减乘除运算:初学者指南

原文地址: https://www.cveoy.top/t/topic/pxhE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录