题目要求:定义一个不受计算机字长限制的整数类INT,要求INT与INT以及INT与C++基本数据类型int之间能进行+、-、×、÷和=运算,
并且能通过cout输出INT类型的值。
一直就在构思这个程序肿么写,然后稍微有了一点点构思,但是由于我太笨了,所以今天只实现了+的一半的操作,但是呢,不想码了,今天先碎告了。明天继续加油~
文件清单:
main.cpp
#include "NewInt.h"
void main(){
char s[] = {'-','5','6','2',NULL};
char s1[] = {'-','4','5','3','4',NULL};
NewInt new1(s,3);
NewInt new2(s1,4);
new1.show();
new2.show();
NewInt new3 = new1+new2;
new3.show();
}
NewInt.cpp
#include <iostream>
using namespace std;
#include "NewInt.h"
void NewInt::show(){
if (array[0]==-1)
{
cout<<"-";
}else{
cout<<0;
}
for (int i = 1;i<length;i++)
{
cout<<array[i];
}
cout<<" ";
}
NewInt::NewInt(){
length = 0;
array[0] = 0;
}
NewInt::NewInt(const char*s,int len){
if (s[0]=='-')
{
array[0] = -1;
for(int i = 1;i<=len;i++){
array[i] = s[i]-'0';
}
}else {
array[0] = 0;
for (int i = 1;i<=len;i++)
{
array[i] = s[i-1]-'0';
}
}
length = len+1;
//length=len+1的原因是因为我们该数字的第一位是用来表示正负号的。
}
NewInt NewInt::operator +(NewInt &ni){
NewInt temp;
temp.array[0]=0;
if (array[0]==0&&ni.array[0]==0)
{
if (length>=ni.length)
{
ni.changeToLonger(length);
temp.length = length;
}else{
changeToLonger(ni.length);
temp.length = ni.length;
}
for (int i1 = 1;i1<temp.length;i1++)
{
temp.array[i1]=0;
}
for(int i = length -1;i>=1;i--){
if (array[i]+ni.array[i]<=9)
{
temp.array[i]+= array[i]+ni.array[i];
}else {
temp.array[i] += array[i]+ni.array[i]-10;
temp.array[i-1]+=1;
}
}
}else if (array[0]==0&&ni.array[0]==-1)
{
}else if (array[0]==-1&&ni.array[0]==0)
{
}else {
temp.array[0]=-1;
if (length>=ni.length)
{
ni.changeToLonger(length);
temp.length = length;
}else{
changeToLonger(ni.length);
temp.length = ni.length;
}
for (int i1 =1;i1<temp.length;i1++)
{
temp.array[i1] = 0;
}
for(int i = length -1;i>=1;i--){
if (array[i]+ni.array[i]<=9)
{
temp.array[i]+= array[i]+ni.array[i];
}else {
temp.array[i] += array[i]+ni.array[i]-10;
temp.array[i-1]+=1;
}
}
if (temp.array[0]>=0)
{
for (int i = temp.length;i>0;i--)
{
temp.array[i] = temp.array[i-1];
}
temp.array[0] = -1;
temp.length++;
}
}
return temp;
}
void NewInt::changeToLonger(int len){
if (array[0]==0)
{
for (int i = len-1;i>len-length-1;i--)
{
array[i]=array[i-(len-length)];
}
for (int j = 1;j<=len-length-1;j++)
{
array[j] = 0;
}
length = len;
}else if (array[0]==-1)
{
for (int i = len-1;i>len-length;i--)
{
array[i]=array[i-(len-length)];
}
for (int j = 1;j<=len-length;j++)
{
array[j] = 0;
}
length = len;
}
}
NewInt.h
#include <cstring>
#define MAX 100
class NewInt{
private:
int array[MAX];
int length;
public:
NewInt();
NewInt(const char*s,int len);
void show();
void changeToLonger(int len);
NewInt operator +(NewInt &ni);
NewInt operator -(NewInt &ni);
NewInt operator *(NewInt &ni);
NewInt operator /(NewInt &ni);
};
随着代码的完善,继续往上加或者修改。