Buatlah fungsi yang menentukan nilai terbesar dari 2 bilangan bulat
c++ :
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
int a,b;
cout<<"masukkan nilai pertama :";cin>>a;
cout<<"masukkan nilai kedua :";cin>>b;
if(a>b){
cout<<"angka terbesar :"<<a;
}
else{
cout<<"angka terkecil :"<<b;
}
return 0;
}
raptor :
KASUS 5.3
Dengan menggunakan fungsi ln dan exp, buatlah fungsi untuk menghasilkan nilai xy
c++:
#include <iostream>
#include <math.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
float pangkat(int x, int y)
{ return(exp(y*log(x))); }
int main(int argc, char** argv) {
float hasil;
int a, b;
cout << "Menghitung hasil perpangkatan\n";
cout << "masukkan sebuah bilangan : "; cin >> a;
cout << "Mau dipangkat berapa : "; cin >> b;
hasil = pangkat(a,b);
cout << a << " pangkat " << b << " = " << hasil;
return 0;
}
raptor:
KASUS 5.4
Buatlah fungsi perkalian dua bilangan bulat dengan menggunakan operator penjumlahan
c++:
#include <iostream>
#include <math.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int kali (int m,int n){
int i,hasil=0;
for(i=1;i<=abs(n)i++);
hasil+=m;
if(n<0) return(-hasil);
else return(hasil);
}
int main(int argc, char** argv) {
int a,b;
cout<<"masukkan bilangan :";cin>>a;
cout<<"akan dikali dengan :";cin>>b;
cout<<"Nilai"<<a<<"x"<<b<<"="<<kali(a,b);
return 0;
}
KASUS 5.5
Buatlah fungsi faktorial secara rekursif untuk mencari n!
c++:
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int factorial (int n, int x, int hasil){
if(x>n){
cout<<"factorial "<<n<<" adalah "<<hasil<<endl;
}
else{
hasil=hasil*x;
x=x+1;
factorial(n,x,hasil);
}
}
int main(int argc, char** argv) {
int hasil,n,x;
cout<<"masukkan nilai factorial :";cin>>n;
x=1;
hasil=1;
factorial(n,x,hasil);
return 0;
}
KASUS 5.6
C++:
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int fibonacci (int n){
if ((n == 1) || (n == 2)) return(1);
else return(fibonacci(n-1) + fibonacci(n-2));
}
int main(int argc, char** argv) {
int i, n;
cout << "Sampai suku ke : "; cin >> n;
for (i = 1; i <= n; i++) cout << fibonacci(i) << " ";
return 0;
}
Tidak ada komentar:
Posting Komentar