我需要一个C语言代码,完成以下操作:编写两个任意位数的大数相加、相乘的程序,给出计算结果。
时间: 2024-02-12 14:07:24 浏览: 83
好的,以下是一个简单的实现方式:
```c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_SIZE 1000
void reverse(char* str) {
int len = strlen(str);
for(int i = 0; i < len/2; i++) {
char temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}
}
void add(char* num1, char* num2, char* result) {
int len1 = strlen(num1);
int len2 = strlen(num2);
int len = len1 > len2 ? len1 : len2;
reverse(num1);
reverse(num2);
int carry = 0;
for(int i = 0; i < len; i++) {
int n1 = i < len1 ? num1[i] - '0' : 0;
int n2 = i < len2 ? num2[i] - '0' : 0;
int sum = n1 + n2 + carry;
result[i] = sum % 10 + '0';
carry = sum / 10;
}
if(carry != 0) {
result[len] = carry + '0';
len++;
}
result[len] = '\0';
reverse(result);
}
void multiply(char* num1, char* num2, char* result) {
int len1 = strlen(num1);
int len2 = strlen(num2);
int len = len1 + len2;
int* temp = (int*)malloc(sizeof(int) * len);
memset(temp, 0, sizeof(int) * len);
reverse(num1);
reverse(num2);
for(int i = 0; i < len1; i++) {
for(int j = 0; j < len2; j++) {
temp[i+j] += (num1[i] - '0') * (num2[j] - '0');
}
}
int carry = 0;
for(int i = 0; i < len; i++) {
int sum = temp[i] + carry;
result[i] = sum % 10 + '0';
carry = sum / 10;
}
while(len > 0 && result[len-1] == '0') {
len--;
}
result[len] = '\0';
reverse(result);
free(temp);
}
int main() {
char num1[MAX_SIZE], num2[MAX_SIZE], result[MAX_SIZE*2];
printf("Please enter two big numbers:\n");
scanf("%s %s", num1, num2);
add(num1, num2, result);
printf("The sum is: %s\n", result);
multiply(num1, num2, result);
printf("The product is: %s\n", result);
return 0;
}
```
该代码中,我们定义了 `add` 和 `multiply` 两个函数,分别用于实现大数相加和大数相乘的操作。我们先输入两个大数,然后调用这两个函数计算它们的和和积,并输出结果。这里的大数指的是位数在 1000 以内的整数。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)