从键盘输入的字符串由二个大正整数组成的字符串。(123456123456123456 1234567890123456789)。(注意: 整数位数超过12位数,整数之间用空格分开。)
完成:对字符串中的整数进行求和,求积。并且显示计算结果。
用devc++编写
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_SIZE 1024
typedef struct { char num[MAX_SIZE]; int size; }big_integer_t;
void init_big_integer(big_integer_t* n)
{
memset(n->num, 0, sizeof(n->num));
n->size = 0;
}
void add_big_integer(const big_integer_t* lhs, big_integer_t* rhs, big_integer_t* result)
{
int lhsi = lhs->size - 1, rhsi = rhs->size - 1;
result->size = 0;
int addition = 0;
while (lhsi >= 0 || rhsi >= 0 || addition > 0)
{
addition += (lhsi >= 0 ? (lhs->num[lhsi] - '0') : 0)
+ (rhsi >= 0 ? (rhs->num[rhsi] - '0') : 0);
result->num[result->size++] = (addition % 10) + '0';
addition /= 10;
if (lhsi >= 0)lhsi--;
if (rhsi >= 0)rhsi--;
}
result->num[result->size] = 0;
strrev(result->num);
}
void mul_big_integer(const big_integer_t* lhs, big_integer_t* rhs, big_integer_t* result)
{
big_integer_t tmp;
init_big_integer(&tmp);
result->size = 0;
for (int i = rhs->size - 1; i >= 0; --i)
{
int rn = rhs->num[i] - '0';
int addition = 0;
tmp.size = 0;
for (int j = lhs->size - 1; j >= 0; --j)
{
int ln = lhs->num[j] - '0';
addition += rn * ln;
tmp.num[tmp.size++] = addition % 10 + '0';
addition /= 10;
}
while (addition > 0)
{
tmp.num[tmp.size++] = addition % 10 + '0';
addition /= 10;
}
tmp.num[tmp.size] = 0;
big_integer_t tmp2 = *result;
int lhsi = 0, rhsi = (rhs->size - i - 1);
result->size = rhsi;
addition = 0;
while (lhsi < tmp.size || rhsi < tmp2.size || addition > 0)
{
addition += (lhsi < tmp.size ? (tmp.num[lhsi] - '0') : 0)
+ (rhsi < tmp2.size ? (tmp2.num[rhsi] - '0') : 0);
result->num[result->size++] = (addition % 10) + '0';
addition /= 10;
if (lhsi < tmp.size)lhsi++;
if (rhsi < tmp2.size)rhsi++;
}
}
result->num[result->size] = 0;
strrev(result->num);
}
int add_two_big_integer() {
char str[2048];
memset(str, 0, sizeof(str));
int i = 0, sum = 0, quadrature = 1;
printf("请输入字符串:\n");
gets(str);
int len = strlen(str);
big_integer_t num0, num1, result_add, result_mul;
init_big_integer(&num0);
init_big_integer(&num1);
init_big_integer(&result_add);
init_big_integer(&result_mul);
// 读取第一个大整数
while (i < len && !isdigit(str[i]))++i;
while (i < len && isdigit(str[i]))num0.num[num0.size++] = str[i++];
num0.num[num0.size] = 0;
// 读取第二个大整数
while (i < len && !isdigit(str[i]))++i;
while (i < len && isdigit(str[i]))num1.num[num1.size++] = str[i++];
num1.num[num1.size] = 0;
// 相加
add_big_integer(&num0, &num1, &result_add);
// 相乘
mul_big_integer(&num0, &num1, &result_mul);
printf("字符串中所有正整数之和为:%s,所有正整数之积为:%s\n",
result_add.num,
result_mul.num);
return 0;
}
int main() {
add_two_big_integer();
}