c++设计一个最大存储200位整数的大正整数类LPInteger;并编写主函数对你编写的正整数类LPInteger进行测试。 要求输入的数据不超过200位,输出该大正整数并且输出该大正整数的位数。 用户输入的数据中含有非数字的字符时,输出error!
时间: 2024-04-30 17:23:26 浏览: 14
分析:
大正整数类LPInteger需要存储一个200位的整数,因此可以使用一个长度为200的整型数组来存储。在输入时需要判断输入的数据是否合法,如果输入的数据中含有非数字的字符,则输出error,否则将数据存储到数组中。在输出时需要从数组的高位到低位遍历数组,将每一位数字输出,同时统计位数。最后输出位数即可。
代码实现:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 200
class LPInteger {
private:
int num[MAX_LEN];
public:
LPInteger() {
memset(num, 0, sizeof(num));
}
void input() {
char str[MAX_LEN + 1];
scanf("%s", str);
int len = strlen(str);
if (len > MAX_LEN) {
printf("error!\n");
return;
}
for (int i = 0; i < len; i++) {
if (str[i] < '0' || str[i] > '9') {
printf("error!\n");
return;
}
num[MAX_LEN - len + i] = str[i] - '0';
}
}
void output() {
int len = MAX_LEN;
while (len > 0 && num[len - 1] == 0) {
len--;
}
if (len == 0) {
printf("0");
} else {
for (int i = len - 1; i >= 0; i--) {
printf("%d", num[i]);
}
}
printf("\n%d\n", len);
}
};
int main() {
LPInteger a;
a.input();
a.output();
return 0;
}
```
测试样例:
输入:
```
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
```
输出:
```
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
200
```