Algoritma mencari rata-rata {diberikan n data kemudian dicari rata-ratanya} |
Deklarasi i, n, jumlah, x : integer rata : real |
Deskripsi read(n) jumlah = 0 for i = 1 to n do read(x) jumlah = jumlah + x endfor rata = jumlah/n write(rata) |
Listing
#include <iostream> |
#include <conio.h> |
#include <cstdlib> |
using namespace std; |
class Rata{ |
friend istream& operator>>(istream&, Rata&); |
friend ostream& operator<<(ostream&, Rata&); |
public : |
float hitung_rata(); |
private : |
int n; |
int data; |
}; |
istream& operator>>(istream& in, Rata& A){ |
cout<<"BANYAK DATA : "; |
in>>A.n; |
return in; |
} |
float Rata::hitung_rata(){ |
int jumlah = 0; |
float rata; |
for(int i = 1; i<=n; i++){ |
cout<<"\ndata ke- "<<i<<" : "; |
cin>>data; |
jumlah = jumlah + data; |
} |
rata = (float)jumlah/n; |
return rata; |
} |
ostream& operator<<(ostream&, Rata&A){ |
cout << "\nRATA-RATA : " << A.hitung_rata(); |
return cout; |
} |
int main(){ |
Rata x; |
cin>>x; |
cout<<x; |
getch(); |
} |
Tidak ada komentar:
Posting Komentar