Jumat, 20 Juni 2014
Contoh Codingan Faktorial, Fibonanci & Biner Calculating C++
#include<iostream>
using namespace std;
class Bilangan
{
private:
long angka;
long hasil;
public:
//Bilangan(int hasil){hasil = 0;}
void setAngka(long angka)
{
this->angka = angka;
}
friend long getAngka(Bilangan &obj)
{
return obj.angka;
}
long getHasil() const{return hasil;}
void biner(int angka )
{
if(angka == 0)cout << "0 ";
else
{
biner(angka/2);
cout << angka%2 << " ";
}
}
int fibonacci(long angka);
~Bilangan(){}
};
int Bilangan::fibonacci(long angka)
{
if(angka == 0 || angka == 1)return angka;
else return fibonacci(angka - 1) + fibonacci(angka - 2);
}
inline long long int faktorial(Bilangan &obj)
{
long long temp=1;
for(int i = 1;i <= getAngka(obj);i++)
{
//cout << temp << endl;
temp *= i;
}
return temp;
}
void clear()
{
for(int i=0;i<25;i++)cout<<endl;
}
void menu()
{
cout << "Factorial, Fibonacci, and Biner Calculation" << endl
<< "===========================================" << endl << endl ;
cout << "1. Factorial" << endl;
cout << "2. Fibonacci" << endl;
cout << "3. Binary Number" << endl;
cout << "4. Exit" << endl;
}
void main()
{
Bilangan obj;
//cont object , atribut dr object tidak dapat dirubah
const Bilangan b;
int opt;
long long angka;
do
{
opt = 0;
clear();
menu();
do
{
cout << "Choose: ";
cin >> opt;cin.clear();cin.sync();
}while(opt < 1 || opt >4);
switch(opt)
{
case 1:
clear();
do
{
cout << "Input the number[1-20]: ";
cin >> angka;cin.clear();cin.sync();
}while(angka < 1|| angka > 20);
obj.setAngka(angka);
cout << endl << "The Result of Factorial " << getAngka(obj) << " : " << endl;
cout << faktorial(obj) << " ";
cin.get();
break;
case 2:
clear();
do
{
cout << "Input the number[1-20]: ";
cin >> angka;cin.clear();cin.sync();
}while(angka < 1|| angka > 20);
obj.setAngka(angka);
cout << endl << "The Result of Fibonacci " << getAngka(obj) << " : " << endl;
for(int i = 0;i< getAngka(obj);i++)
cout << obj.fibonacci(i) << " ";
cin.get();
break;
case 3:
clear();
do
{
cout << "Input the number[1-100]: ";
cin >> angka;cin.clear();cin.sync();
}while(angka < 1|| angka > 100);
obj.setAngka(angka);
cout << endl << "The Result of Binary Number " << getAngka(obj) << " : " << endl;
obj.biner(getAngka(obj));
cin.get();
break;
case 4:
clear();
cout << endl << endl << " Thank you and have a nice day.. ^^" << endl;
break;
}
}while(opt != 4);
cin.get();
}
Langganan:
Posting Komentar (Atom)
Tidak ada komentar:
Posting Komentar