已知A、B分别是m、n位(位数为10-30的随机正整数)的随机正整数,编写程序给出这两个数相加结果。如:A=47858628539074,B= 212821064467,C=A+B=48071449603541 C语言
时间: 2024-06-02 07:14:23 浏览: 73
#include <stdio.h>
#include <string.h>
#define MAX_N 30
void reverse(char s[], int len)
{
for (int i = 0; i < len / 2; i++) {
char tmp = s[i];
s[i] = s[len - i - 1];
s[len - i - 1] = tmp;
}
}
void add(char a[], char b[], char c[])
{
int len_a = strlen(a);
int len_b = strlen(b);
int len_c = len_a > len_b ? len_a : len_b;
int carry = 0;
for (int i = 0; i < len_c; i++) {
int digit_a = i < len_a ? a[i] - '0' : 0;
int digit_b = i < len_b ? b[i] - '0' : 0;
int sum = digit_a + digit_b + carry;
carry = sum / 10;
c[i] = sum % 10 + '0';
}
if (carry) {
c[len_c] = carry + '0';
len_c++;
}
c[len_c] = '\0';
reverse(c, len_c);
}
int main()
{
char a[MAX_N + 1];
char b[MAX_N + 1];
char c[MAX_N + 2];
printf("Please enter two positive integers:\n");
scanf("%s%s", a, b);
add(a, b, c);
printf("The sum is: %s\n", c);
return 0;
}
阅读全文