Program C++ Menghitung Mean Modus Median Dan Deviasi - Bryan Reinaldo 06

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

PROGRAM C++ MENGHITUNG MEAN, MODUS, MEDIAN DAN DEVIASI SUAT BILANGAN

Bryan Reinaldo XII MIPA 2/06

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;

// Fungsi untuk menghitung Mean (rata-rata)


double mean(const vector<double>& data) {
double total = 0.0;
for (const double& value : data) {
total += value;
}
return total / data.size();
}

// Fungsi untuk menghitung Median


double median(vector<double>& data) {
sort(data.begin(), data.end());
int size = data.size();
if (size % 2 == 0) {
return (data[size / 2 - 1] + data[size / 2]) / 2.0;
} else {
return data[size / 2];
}
}
// Fungsi untuk menghitung Modus
vector<double> mode(const vector<double>& data) {
vector<double> modes;
int maxFrequency = 1;
int currentFrequency = 1;

for (size_t i = 1; i < data.size(); i++) {


if (data[i] == data[i - 1]) {
currentFrequency++;
} else {
currentFrequency = 1;
}

if (currentFrequency > maxFrequency) {


maxFrequency = currentFrequency;
}
}

currentFrequency = 1;

for (size_t i = 1; i < data.size(); i++) {


if (data[i] == data[i - 1]) {
currentFrequency++;
} else {
currentFrequency = 1;
}

if (currentFrequency == maxFrequency && find(modes.begin(), modes.end(), data[i]) ==


modes.end()) {
modes.push_back(data[i]);
}
}

return modes;
}

// Fungsi untuk menghitung Deviasi


double deviasi(const vector<double>& data, double meanValue) {
double totalSquaredDifference = 0.0;

for (const double& value : data) {


double difference = value - meanValue;
totalSquaredDifference += difference * difference;
}

return sqrt(totalSquaredDifference / data.size());


}

int main() {
int n;
vector<double> data;

cout <<"SELAMAT DATANG"<<endl;


cout <<"DI WEBSITE PENGHITUNG MEAN, MEDIAN,MODUS DAN DEVIASI"<<endl;
cout <<"HANYA PERLU MEMASUKKAN BILANGAN YANG DIPILIH"<<endl;
cout <<endl;
cout << "Masukkan jumlah bilangan: ";
cin >> n;
cout << "Masukkan " << n << " bilangan: ";
for (int i = 0; i < n; i++) {
double value;
cin >> value;
data.push_back(value);
}

double meanValue = mean(data);


double medianValue = median(data);
vector<double> modes = mode(data);
double deviationValue = deviasi(data, meanValue);

cout << "Mean (rata-rata): " << meanValue << endl;


cout << "Median: " << medianValue << endl;
cout << "Modus: ";
for (const double& modeValue : modes) {
cout << modeValue << " ";
}
cout << endl;
cout << "Deviasi: " << deviationValue << endl;
cout << endl;
cout << "CODING BY BRYAN REINALDO - SMAN 1 GEDANGAN";
return 0;
}

You might also like