大整数计算器c语言代码
时间: 2023-08-31 07:09:55 浏览: 69
以下是一个简单的大整数计算器的 C 代码。它可以执行加法、减法、乘法和除法运算。
```
#include <stdio.h>
#include <string.h>
#define MAX_DIGITS 1000
typedef struct {
int digits[MAX_DIGITS];
int size;
} Bigint;
void init(Bigint *n) {
memset(n->digits, 0, sizeof(n->digits));
n->size = 0;
}
void from_int(Bigint *n, int x) {
init(n);
do {
n->digits[n->size++] = x % 10;
x /= 10;
} while (x > 0);
}
void from_string(Bigint *n, char *str) {
init(n);
int len = strlen(str);
for (int i = len - 1; i >= 0; i--) {
n->digits[n->size++] = str[i] - '0';
}
}
void print(Bigint *n) {
for (int i = n->size - 1; i >= 0; i--) {
printf("%d", n->digits[i]);
}
}
int compare(Bigint *a, Bigint *b) {
if (a->size != b->size) {
return a->size - b->size;
}
for (int i = a->size - 1; i >= 0; i--) {
if (a->digits[i] != b->digits[i]) {
return a->digits[i] - b->digits[i];
}
}
return 0;
}
void add(Bigint *a, Bigint *b, Bigint *c) {
init(c);
int carry = 0;
for (int i = 0; i < a->size || i < b->size || carry > 0; i++) {
int x = carry;
if (i < a->size) {
x += a->digits[i];
}
if (i < b->size) {
x += b->digits[i];
}
c->digits[c->size++] = x % 10;
carry = x / 10;
}
}
void subtract(Bigint *a, Bigint *b, Bigint *c) {
init(c);
int borrow = 0;
for (int i = 0; i < a->size || i < b->size; i++) {
int x = borrow;
if (i < a->size) {
x += a->digits[i];
}
if (i < b->size) {
x -= b->digits[i];
}
if (x < 0) {
x += 10;
borrow = -1;
} else {
borrow = 0;
}
c->digits[c->size++] = x;
}
while (c->size > 1 && c->digits[c->size - 1] == 0) {
c->size--;
}
}
void multiply(Bigint *a, Bigint *b, Bigint *c) {
init(c);
for (int i = 0; i < a->size; i++) {
int carry = 0;
for (int j = 0; j < b->size || carry > 0; j++) {
int x = carry;
if (j < b->size) {
x += a->digits[i] * b->digits[j];
}
if (i + j < c->size) {
x += c->digits[i + j];
}
if (x > 9) {
carry = x / 10;
x %= 10;
} else {
carry = 0;
}
c->digits[i + j] = x;
}
}
while (c->size > 1 && c->digits[c->size - 1] == 0) {
c->size--;
}
}
void divide(Bigint *a, Bigint *b, Bigint *c) {
init(c);
Bigint r;
init(&r);
for (int i = a->size - 1; i >= 0; i--) {
r.digits[0] = a->digits[i];
r.size = 1;
int x = 0, y = 9;
while (x <= y) {
int m = (x + y) / 2;
Bigint t, p;
from_int(&t, m);
multiply(b, &t, &p);
if (compare(&p, &r) <= 0) {
x = m + 1;
} else {
y = m - 1;
}
}
c->digits[i] = y;
Bigint t, p;
from_int(&t, y);
multiply(b, &t, &p);
subtract(&r, &p, &r);
}
while (c->size > 1 && c->digits[c->size - 1] == 0) {
c->size--;
}
}
int main() {
Bigint a, b, c;
char op;
scanf("%s %c %s", a.digits, &op, b.digits);
from_string(&a, a.digits);
from_string(&b, b.digits);
if (op == '+') {
add(&a, &b, &c);
} else if (op == '-') {
subtract(&a, &b, &c);
} else if (op == '*') {
multiply(&a, &b, &c);
} else if (op == '/') {
divide(&a, &b, &c);
}
print(&c);
return 0;
}
```
注:这个代码只是一个简单的实现,并没有考虑性能和错误处理。实际使用时需要进行更多的测试和优化。