2.已知A、B分别是m、n位(位数为10-30的随机正整数)的随机正整数,编写程序给出这两个正整数相加的结果。如:A=47858628539074,B= 212821064467,C=A+B=48071449603541 用c语言表示
时间: 2023-06-01 19:02:23 浏览: 97
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_DIGITS 30
int main() {
srand(time(NULL));
// 生成两个随机正整数
int m = rand() % (MAX_DIGITS - 10 + 1) + 10;
int n = rand() % (MAX_DIGITS - 10 + 1) + 10;
int A[m], B[n];
for (int i = 0; i < m; i++) {
A[i] = rand() % 10;
}
for (int i = 0; i < n; i++) {
B[i] = rand() % 10;
}
// 将两个正整数相加
int C[MAX_DIGITS] = {0};
int i = m - 1, j = n - 1, k = MAX_DIGITS - 1;
while (i >= 0 || j >= 0) {
int sum = C[k] + (i >= 0 ? A[i] : 0) + (j >= 0 ? B[j] : 0);
C[k] = sum % 10;
C[k - 1] += sum / 10;
i--;
j--;
k--;
}
// 打印结果
printf("A = ");
for (int i = 0; i < m; i++) {
printf("%d", A[i]);
}
printf("\nB = ");
for (int i = 0; i < n; i++) {
printf("%d", B[i]);
}
printf("\nC = ");
for (int i = 0; i < MAX_DIGITS; i++) {
if (C[i] != 0) {
for (int j = i; j < MAX_DIGITS; j++) {
printf("%d", C[j]);
}
break;
}
}
printf("\n");
return 0;
}
阅读全文