用c语言写顺序表.已知A、B分别是m、n位(位数为10-30的随机正整数)的随机正整数,编写程序给出这两个正整数相加的结果。如:A=47858628539074,B= 212821064467,C=A+B=48071449603541
时间: 2024-05-24 10:10:17 浏览: 72
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_LEN 30
typedef struct {
int *data;
int len;
} SeqList;
void initList(SeqList *L, int len) {
L->data = (int *)malloc(len * sizeof(int));
L->len = len;
srand(time(NULL));
for (int i = 0; i < len; i++) {
L->data[i] = rand() % 10;
}
}
void printList(SeqList L) {
for (int i = 0; i < L.len; i++) {
printf("%d", L.data[i]);
}
printf("\n");
}
void add(SeqList A, SeqList B, SeqList *C) {
int carry = 0;
int i = A.len - 1;
int j = B.len - 1;
int k = C->len - 1;
while (i >= 0 || j >= 0) {
int sum = carry;
if (i >= 0) {
sum += A.data[i];
i--;
}
if (j >= 0) {
sum += B.data[j];
j--;
}
C->data[k] = sum % 10;
carry = sum / 10;
k--;
}
if (carry > 0) {
C->data[k] = carry;
}
}
int main() {
SeqList A, B, C;
int lenA = rand() % (MAX_LEN - 9) + 10; // 10-30位随机正整数
int lenB = rand() % (MAX_LEN - 9) + 10;
initList(&A, lenA);
initList(&B, lenB);
C.len = (lenA > lenB ? lenA : lenB) + 1;
C.data = (int *)malloc(C.len * sizeof(int));
add(A, B, &C);
printf("A = ");
printList(A);
printf("B = ");
printList(B);
printf("C = ");
printList(C);
free(A.data);
free(B.data);
free(C.data);
return 0;
}
阅读全文