minerva
main.cpp
2.6 KB · 111 lines
1// 1. read float values from floatvalues.txt into a file buffer2// 2. sum all values and output to the console3// 3. output the highest value to the console4// 4. output the lowest value to the console5// 5. append sum and mean average to the end of floatvalues.txt67#include "main.h"89#include <fstream>10#include <iomanip>11#include <iostream>1213// constructor: read float values from floatvalues.txt into the array14FloatValues::FloatValues() {15 int i = 0;16 std::ifstream file("floatvalues.txt");1718 if (file.is_open()) {19 double value;2021 while (file >> value) {22 values[i] = value;23 i++;24 }25 file.close();26 }27}2829// method 1: output all values30void FloatValues::output_all_values() {3132 for (int i = 0; i < 11; i++) {33 std::cout << values[i] << "\n";34 }35}3637// method 2: add up all values in the array38double FloatValues::get_sum() {39 double sum = 0;4041 for (int i = 0; i < 11; i++) {42 sum = sum + values[i];43 }44 return sum;45}4647// method 3: output sum of all values48void FloatValues::output_sum() { std::cout << "sum: " << get_sum() << "\n"; }4950// method 4: output highest value51void FloatValues::output_highest_value() {52 double highest_val = values[0];5354 for (int i = 0; i < 11; i++) {55 if (values[i] > highest_val) {56 highest_val = values[i];57 }58 }59 std::cout << "highest value: " << highest_val << "\n";60}6162// method 5: output lowest value63void FloatValues::output_lowest_value() {64 double lowest_val = values[0];6566 for (int i = 0; i < 11; i++) {67 if (values[i] < lowest_val) {68 lowest_val = values[i];69 }70 }71 std::cout << "lowest value: " << lowest_val << "\n";72}7374// method 6: mean average75double FloatValues::get_mean_average() { return get_sum() / 11; }7677// method 7: output mean average78void FloatValues::output_mean_average() {79 std::cout << "mean average: " << get_mean_average() << "\n";80}8182// method 8: append sum and mean average to the end of floatvalues.txt83void FloatValues::append_results() {84 std::ofstream file("floatvalues.txt", std::ios::app);8586 if (file.is_open()) {87 file << std::fixed << std::setprecision(2);88 file << "\nsum: " << get_sum() << "\n";89 file << "mean average: " << get_mean_average() << "\n";90 file.close();91 }92}9394int main() {9596 FloatValues midterm;9798 // show 2 decimal places for every number99 std::cout << std::fixed << std::setprecision(2);100101 // midterm.output_all_values();102 // midterm.output_sum();103 // midterm.output_highest_value();104 // midterm.output_lowest_value();105 midterm.output_mean_average();106 // midterm.append_results();107108 return 0;109}110111// g++ -std=c++17 -o midterm main.cpp