用c语言编写程序编写程序实现两个超长整数大于等于0每个最长80位数字的乘法运算。
#include <stdio.h>
#include <string.h>
#define MAX_LEN 81
void reverse(char *str) {
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char tmp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = tmp;
}
}
void multiply(char *a, char *b, char *result) {
int len_a = strlen(a);
int len_b = strlen(b);
int len_result = len_a + len_b;
int carry = 0;
memset(result, '0', len_result);
reverse(a);
reverse(b);
for (int i = 0; i < len_a; i++) {
carry = 0;
for (int j = 0; j < len_b; j++) {
int digit = (a[i] - '0') * (b[j] - '0') + (result[i+j] - '0') + carry;
carry = digit / 10;
result[i+j] = digit % 10 + '0';
}
if (carry > 0) {
result[i+len_b] += carry;
}
}
reverse(result);
while (result[0] == '0' && len_result > 1) {
memmove(result, result + 1, len_result - 1);
len_result--;
}
result[len_result] = '\0';
}
int main() {
char a[MAX_LEN];
char b[MAX_LEN];
char result[MAX_LEN * 2];
printf("Enter the first number: ");
scanf("%s", a);
printf("Enter the second number: ");
scanf("%s", b);
multiply(a, b, result);
printf("The result is: %s\n", result);
return 0;
}
``
原文地址: http://www.cveoy.top/t/topic/hoAL 著作权归作者所有。请勿转载和采集!