用c写一个顺序表.已知A、B分别是m、n位(位数为10-30的随机正整数)的随机正整数,编写程序给出这两个正整数相加的结果。如:A=47858628539074,B= 212821064467,C=A+B=48071449603541
时间: 2024-05-22 18:12:50 浏览: 66
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 30
typedef struct {
int data[MAXSIZE];
int length;
} SqList;
void initList(SqList *L) {
L->length = 0;
}
void input(SqList *L) {
char s[MAXSIZE];
scanf("%s", s);
int i = 0;
while (s[i] != '\0') {
L->data[i] = s[i] - '0';
i++;
}
L->length = i;
}
void add(SqList A, SqList B, SqList *C) {
int carry = 0, sum;
int i = A.length - 1, j = B.length - 1, k = 0;
while (i >= 0 || j >= 0 || carry != 0) {
sum = carry;
if (i >= 0) {
sum += A.data[i];
i--;
}
if (j >= 0) {
sum += B.data[j];
j--;
}
C->data[k] = sum % 10;
k++;
carry = sum / 10;
}
C->length = k;
}
void output(SqList L) {
for (int i = L.length - 1; i >= 0; i--) {
printf("%d", L.data[i]);
}
printf("\n");
}
int main() {
SqList A, B, C;
initList(&A);
initList(&B);
input(&A);
input(&B);
add(A, B, &C);
output(C);
return 0;
}
阅读全文