Модераторы: bsa
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Реализация класса. Классы для работы с целыми числами 
:(
    Опции темы
Neotwalker
Дата 6.6.2016, 19:34 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 3
Регистрация: 3.3.2016

Репутация: нет
Всего: нет



Библиотека классов для работы с целыми числами большой точности
Реализовать класс для работы с целыми десятичными числами с заданным
в аргументе конструктора числом цифр.
Реализовать операции +, -, *, +=, -=, *=, =, сравнения (6 шт.), 
ввода-вывода (<<, >>) для чисел указанного класса, 
а также операции +, -, *, /, +=, -=, *=, /=, =, сравнения (6 шт.), 
где вторым операндом является число long (все) или double (кроме /). 
double используется для записи чисел c большим числом нулей типа 2e100

bigint.h

#include <iostream>
#include <cstring>
using namespace std;
class BigInt {
   // к этим членам можно закрыть доступ
unsigned long Size, SizeMax; // Size – текущая длина
// SizeMax – максимальная длина
short *Coef; // Массив коэффициентов
public:
BigInt(unsigned long a=15):Size(0),SizeMax(a),Coef(new short[a]){} //Конструктор
BigInt(const BigInt&); //Конструктор копирования
~BigInt(){delete[]Coef;} //Деструктор
BigInt operator+(const BigInt)const;
BigInt operator+(const long)const;
BigInt operator+(const double)const;
BigInt operator-(const BigInt)const;
BigInt operator-(const long)const;
BigInt operator-(const double)const;
BigInt operator*(const BigInt)const;
BigInt operator*(const long)const;
BigInt operator*(const double)const;
BigInt operator/(const long)const;
BigInt& operator+=(const BigInt&);
BigInt& operator+=(const long);
BigInt& operator+=(const double);
BigInt& operator-=(const BigInt&);
BigInt& operator-=(const long);
BigInt& operator-=(const double);
BigInt& operator*=(const BigInt&);
BigInt& operator*=(const long);
BigInt& operator*=(const double);
BigInt& operator/=(const long);
bool operator==(const BigInt&)const;
bool operator==(const long)const;
bool operator==(const double)const;
BigInt& operator=(const BigInt&);
BigInt& operator=(const long);
BigInt& operator=(const double);
friend BigInt b_int(const long);
friend BigInt b_int(const double);
friend istream& operator >> (istream &,  BigInt&);
friend ostream& operator << (ostream &, const BigInt&);
};

bigint.cpp

#include "bigint.h"
 
using namespace std;
const long BASE=10;
 
BigInt b_int(const long B){
   unsigned long i=0;
   long A=B;
   do {
      A/=BASE;
      i++;
      } while(A>0);
      BigInt t(i);
      A=B;
   for(unsigned long j=0;j<i; j++){
         t.Coef[j]=B%BASE;
         A/=BASE;
   }
   t.Size=i;
   return t;
}
BigInt b_int(const double B){
   std::string str = std::to_string(B);
   unsigned long i;
   BigInt t(str.size());
   for(i=0;i<str.size(); i++) 
      t.Coef[i]=str[str.size() - i -1]-'0';
   t.Size=i;
   return t;
}
 
//Конструктор копирования
 
BigInt::BigInt(const BigInt& B){
   Size=B.Size;
   SizeMax=B.SizeMax;
   Coef=new short[SizeMax];
   for(unsigned long i=0; i<Size; i++)
      Coef[i]=B.Coef[i];
}
 
//Сложение
 
BigInt BigInt::operator+(const BigInt B)const{
   BigInt t(*this);
   return t+=B;
}
 
BigInt BigInt::operator+(const long B)const{
  BigInt t(*this);
   return t+=B;
   }
   
BigInt BigInt::operator+(const double B)const{
   BigInt t(*this);
   return t+=B;
   }
 
//Вычитание
   
   BigInt BigInt::operator-(const BigInt B)const {
BigInt t(*this);
   return t-=B;
}
 
BigInt BigInt::operator-(const long B )const{
   BigInt t(*this);
   return t-=B;
}
 
BigInt BigInt::operator-(const double B)const{
   BigInt t(*this);
   return t-=B;
}
 
//Умножение
 
BigInt BigInt::operator*(const BigInt B)const{
   BigInt t(*this);
   return t*=B;
}
 
BigInt BigInt::operator*(const long B)const{
  BigInt t(*this);
   return t*=B;
}
 
BigInt BigInt::operator*(const double B)const{
   BigInt t(*this);
   return t*=B;
}
 
//Деление
 
BigInt BigInt::operator/(const long B)const{
   BigInt t(*this);
   return t/=B;
}
 
//
 
BigInt& BigInt::operator+=(const BigInt& B){
   unsigned long i;
short temp; // temp здесь и далее играет роль “временной” цифры,
// до выполнения переноса. Возможно, temp > BASE.
// Здесь и в дальнейших примерах для быстрого доступа к коэффициентам
// объявляются временные указатели a,b,c.
const short *a=Coef, *b=B.Coef;
short carry = 0;
// Добиваемся B.Size ? A.Size.
if ( Size < B.Size ) {
   *this=B+*this;
   return *this;
}
BigInt t(Size+1);
// Теперь B.Size ? A.Size.
// Складываем два числа, i - номер текущей цифры
for (i=0; i<B.Size; i++) {
temp = a[i] + b[i] + carry;
if (temp >= BASE) { // переполнение. Перенести единицу.
t.Coef[i] = temp - BASE;
carry = 1;
} else {
t.Coef[i] = temp;
carry = 0;
}
}
// Меньшее число кончилось
for (; i < Size; i++) {
temp = a[i] + carry;
if (temp >= BASE) {
t.Coef[i] = temp - BASE;
carry = 1;
} else {
t.Coef[i] = temp;
carry = 0;
}
}
// Если остался перенос – добавить его в дополнительный разряд
if (carry) {
t.Coef[i] = carry;
t.Size = i+1;
}
else
   t.Size=i;
   *this=t;
   return *this;
   }
BigInt& BigInt::operator+=(const long B){
   *this+=b_int(B);
   return *this;
}
BigInt& BigInt::operator+=(const double B){
   *this+=b_int(B);
   return *this;
}
 
//Вычесть из данного числа
 
BigInt& BigInt::operator-=(const BigInt& B){
const short *a=Coef, *b=B.Coef;
unsigned long i;
long temp, carry=0;
if ( Size < B.Size ) exit(1);
for (i=0; i<B.Size; i++) {
temp = a[i] - b[i] + carry;
if (temp < 0) {
Coef[i] = temp + BASE;
carry = -1;
} else {
Coef[i] = temp;
carry = 0;
}
}
for (; i<Size; i++) {
temp = a[i] + carry;
if (temp < 0) {
Coef[i] = temp + BASE;
carry = -1;
} else {
Coef[i] = temp;
carry = 0;
}
}
// Размер результата может быть гораздо меньше, чем у исходного числа
// Устанавливаем его по первому положительному разряду
i = Size-1;
while ( (i>0) && (Coef[i]==0) ) i--;
Size = i+1;
   return*this;
}
 
BigInt& BigInt::operator-=(const long B){
   *this-=b_int(B);
   return *this;
}
 
BigInt& BigInt::operator-=(const double B){
   *this-=b_int(B);
   return *this;
}
 
//
 
BigInt& BigInt::operator*=(const BigInt& B){
   unsigned long i, j, temp;
   BigInt t(Size+B.Size+1);
   const short *a=Coef,*b=B.Coef;
   short *c=t.Coef;
   short carry=0;
   for ( i=0; i <= Size+B.Size; i++ ) c[i]=0;
   for ( i = 0; i < Size; i++) {
   carry = 0;
   // вычисление временного результата с одновременным прибавлением
   // его к c[i+j] (делаются переносы)
   for (j = 0; j < B.Size; j++) {
      temp = a[i] * b[j] + c[i+j] + carry;
      carry = temp/BASE;
      c[i+j] = temp%BASE;
   }
   c[i+j] = carry;
   }
   t.Size=i+j-1;
   t.Size+=carry>0?1:0;
   swap(Coef,t.Coef);
   swap(Size,t.Size);
   swap(SizeMax,t.SizeMax);
   return*this;}
BigInt& BigInt::operator*=(const long B){
   *this*=b_int(B);
   return *this;
}
BigInt& BigInt::operator*=(const double B){
   *this*=b_int(B);
   return *this;
}
 
//Деление
 
BigInt& BigInt::operator/=(const long   B){
   BigInt Q(Size);
   short r=0, *q=Q.Coef;
const short *a=Coef;
long i, temp;
for ( i=Size-1; i>=0; i--) { // идти по A, начиная от старшего разряда
temp = r*BASE + a[i]; // r – остаток от предыдущего деления
// вначале r=0, temp – текущая цифра A с
// учетом перенесенного остатка
q[i] = temp / B; // i-я цифра частного
r = temp - q[i]*B; // остаток примет участие в вычислении
// следующей цифры частного
}
// Размер частного меньше, либо равен размера делимого
i = Size-1;
while ( (i>0) && (q[i]==0) ) i--;
Q.Size = i+1;
   swap(Coef,Q.Coef);
   swap(Size,Q.Size);
   swap(SizeMax,Q.SizeMax);
   return*this;}
 
//Сравнение
 
bool BigInt::operator==(const BigInt& B)const{
   if(Size!=B.Size) return false;
   for(unsigned long i=0;i<Size;i++){
      if(Coef[i]!=B.Coef[i])
         return false;
   }
   return true;
}   
bool BigInt::operator==(const long B)const{
   return *this==b_int(B);
}
bool BigInt::operator==(const double B)const{
   return *this==b_int(B);
}
 
//Присвоение
 
BigInt& BigInt::operator=(const BigInt& B){
   BigInt t(B);
   swap(Coef,t.Coef);
   swap(Size,t.Size);
   swap(SizeMax,t.SizeMax);
   return *this;
}
BigInt& BigInt::operator=(const long B){
   *this=b_int(B);
   return *this;
}
 
BigInt& BigInt::operator=(const double B){
   *this=b_int(B);
   return *this;
}
 
 
//Ввод,вывод.
 
istream& operator >> (istream &is,  BigInt& B){
   char *str=new char [100];
   unsigned long i;
   is >> str;
   for(i=0;i<strlen(str);i++){
      B.Coef[strlen(str)-i-1]=str[i]-'0';
   }
   B.Size=i;
   return is;
}
ostream& operator << (ostream &os, const BigInt& B){
   for(unsigned long i=B.Size; i>0;i--)
    os<<B.Coef[i-1];
return os;
}
C++Выделить код

MAIN.cpp

#include <conio.h>
#include "bigint.h"
using namespace std;
int main(){
   BigInt a,b,c(30);
   long x=99999, y=4;
   cout<<"Введите a и b: ";
   cin>>a>>b;
   cout<< "Результат: "<< endl;
   cout<<a<<"\n"<<b<<"\n";
   c=a+b;
   cout<<c<<"\n";
   c=a-b;
   cout<<c<<"\n";
   c=a*b;
   cout<<c<<"\n";
   c/=y;
   cout<<c<<"\n";
   c+=x;
   cout<<c<<"\n";
   c-=x;
   cout<<c<<"\n";
   c*=x;
   cout<<c<<"\n";
   if (a==b)
      cout<<"a=b"<<"\n";
   getch();
   return 0;
   }
Не могу сделать умножение и деление и, вроде как, неправильно работает вычитание, помогите найти ошибки
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "C/C++: Для новичков"
JackYF
bsa

Запрещается!

1. Публиковать ссылки на вскрытые компоненты

2. Обсуждать взлом компонентов и делиться вскрытыми компонентами

  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда
  • Вопросы по реализации алгоритмов рассматриваются здесь


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, JackYF, bsa.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | C/C++: Для новичков | Следующая тема »


 




[ Время генерации скрипта: 0.0413 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.