首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BigInt显示功能

BigInt显示功能
EN

Stack Overflow用户
提问于 2013-02-04 04:28:40
回答 1查看 1.3K关注 0票数 1

我正在为BigInt类实现代码,但在显示对象时遇到问题。我不确定我做错了什么,但我的结果是相反的。请帮帮我!

代码语言:javascript
复制
BigInt.h

#include <iostream>
using namespace std;
using std::cout;

#ifndef BIGINT_H
#define BIGINT_H

class BigInt
{
//input and output operators
    friend istream & operator >> (istream &, BigInt &);
    friend ostream & operator << (ostream &, const BigInt &);

public:
    BigInt(); //default constructor
    BigInt(int); //initializes array with user-specified numbers

    BigInt operator + (BigInt &);

    void display(); //prints array

private:
   static const int CAPACITY = 40;
   int Digits[CAPACITY]; //stores all digits
};
#endif

BigInt.cpp

代码语言:javascript
复制
#include <iostream>
#include "BigInt.h"
using std::cout;

BigInt::BigInt()
{
   for (int i = 0; i < CAPACITY; i++)
      Digits[i] = 0;
}

BigInt::BigInt(int InitNum)
{
   //Inputs the individual numbers given to BigInt into the Digits array's elements
   for(int i = 0; i < CAPACITY; i++)
   {
      if(InitNum > 0)
      {
         Digits[i] = InitNum%10;
         InitNum = InitNum/10;
      }
      else
         Digits[i]=0;
   }
}

//------------------------------------------------------------------
BigInt BigInt::operator +(BigInt & a)
{
   for(int i = CAPACITY - 1; i >= CAPACITY; i--)
      Digits[i]+=a.Digits[i];
}

//-----------------------------------------------------------------
ostream & operator << (ostream & cout, const BigInt& a)
{
   for(int i=0; i< a.CAPACITY ; i++)
      cout << a.Digits[i];
   return cout;
}

istream & operator >> (istream & cin,  BigInt& a)
{
   for(int i = 0; i < a.CAPACITY; ++i)
      cin >> a.Digits[i];

   return cin;
}

//---------------------------------------------------------------
void BigInt::display()
{
   for(int i = 0; i< CAPACITY; i++)
      cout << Digits[i];

   cout << "\n";
}

Main.cpp

代码语言:javascript
复制
#include <iostream>
#include <cstdlib>
#include <fstream>
#include "BigInt.h"

int main()
{
   BigInt object1(45756369);
   BigInt object2(47435892);

   object1.display();
   object2.display();

   BigInt object3 = object1 + object2;

   cout << object3;

   return 0;
}

谢谢!另外,operator+函数还可以吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-04 04:51:45

你把你的数字反向放在构造函数中,Num % 10会给你最后一个数字...在构造函数中填充完数组后,您需要反转数组。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14676939

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档