![]() Ласло Краус |
Објектно програмирање - колоквијуми Први колоквијум 25. 11. 1999 |
---|
I1=I2
),
I1+I2
),
I1+=I2
),
++I
,
I++
),
d>>I
),
d<<I
).
Саставити на језику C++ главни програм који прочита n, израчуна Fn, испише резултат и понавља претходне кораке све док за n не прочита негативну вредност.
// 1999_k1.h - Definicija klase velikih celih brojeva (Int).
#include <iostream.h>
class Int {
int duz; char *cif;
void kopiraj (const Int &);
void brisi () { delete [] cif; duz = 0; }
public:
Int (long k=0);
Int (const Int &I) { kopiraj (I); }
~Int () { brisi (); }
Int & operator= (const Int &I) {
if (this != &I) { brisi (); kopiraj (I); }
return *this;
}
friend Int operator+ (const Int &, const Int &);
Int & operator+= (const Int &I) { return *this = *this + I; }
Int & operator++ () { return *this += 1; }
Int operator++ (int) { Int I = * this; ++*this; return I; }
long vrednost ();
friend istream & operator>> (istream &d, Int &I);
friend ostream & operator<< (ostream &d, const Int &I);
};
// 1999_k1.cpp - Definicije metoda uz klasu Int.
#include "1999_k1.h"
Int::Int (long k) {
char c[10]; duz=0;
do { c[duz++] = (char)(k % 10); k /= 10; } while (k);
cif = new char [duz];
for (int i=0; i<duz; i++) cif[i] = c[i];
}
void Int::kopiraj (const Int &I) {
cif = new char [duz = I.duz];
for (int i=0; i<duz; i++) cif[i] = I.cif[i];
}
Int operator+ (const Int &I1, const Int &I2) {
int duz = (I1.duz > I2.duz ? I1.duz : I2.duz) + 1;
char *cif = new char [duz];
for (int i=0, p=0; i<duz; i++) {
int c = (i >= I1.duz && i >= I2.duz) ? p :
(i >= I2.duz ) ? p + I1.cif[i] :
(i >= I1.duz ) ? p + I2.cif[i] :
p + I1.cif[i] + I2.cif[i];
cif[i] = c % 10; p = c / 10;
}
if (cif[duz-1] == 0) duz--;
Int I; I.cif = new char [I.duz = duz];
for (i=0; i<duz; i++) I.cif[i] = cif[i];
delete [] cif;
return I;
}
long Int::vrednost () {
long k=0;
for (int i=duz; i>0; (k*=10)+=cif[--i]);
return k;
}
#include <string.h>
istream & operator>> (istream &d, Int &I) {
char *cif = new char [500]; d >> cif;
I.brisi(); I.cif = new char [I.duz = strlen(cif)];
for (int i=0; i<I.duz; i++) I.cif[I.duz-i-1] = cif[i] - '0';
delete [] cif;
return d;
}
ostream & operator<< (ostream &d, const Int &I) {
for (int i=I.duz; i>0; d<<(int)I.cif[--i]);
return d;
}
// 1999_k1t.cpp - Izracunavanje Fibonaccijevih brojeva.
#include "1999_k1.h"
#include <iostream.h>
Int fibo (int n) {
Int f0 = 1, f1 = 1;
for (int i=2; i<=n; i++) {
Int f2 = f0 + f1;
f0 = f1;
f1 = f2;
}
return f1;
}
void main () {
while (1) {
cout << "n? "; int n; cin >> n;
if (n < 0) break;
cout << "f= " << fibo (n) << endl << endl;
}
}
(садржај)
Copyright © 2010, Laslo Kraus
Последња ревизија: 4.10.2010.