Why is My output rounding down

I have a program that outputs a list of numbers. The program is working, but the output is supposed to be 7.10 and 9.3. Instead I get 7.00 and 9.00.
This is my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <algorithm>


using namespace std;



int main()
{
    //DATA ABSTRACTION:
    double grades[5];
    int i, j;
    double avg_grade;
    double min_grade;
    double max_grade;
    double med_grade;

    for(i=0;i<=4;i++)
    {
        //INPUT:
        cin >>grades[i];

    }
    //PROCESS:
    for(i=0;i<=3;i++)
    {
        for(j=i+1;j<=4;j++)
        {
            int temp;
            if(grades[i]>grades[j])
            {
                temp=grades[i];
                grades[i] = grades[j];
                grades[j]=temp;

            }
        }
    }
    cout << fixed << setprecision(2);

    //OUTPUT:
    avg_grade = (grades[0]+grades[1]+grades[2]+grades[3]+grades[4])/5;

    med_grade = grades[2];
    min_grade = grades[0];
    max_grade = grades[4];
    
    cout<<med_grade;
    cout<<min_grade;
    cout<<max_grade;

this isn't all of the code just the part that is giving me the porblem.

Your bubble sort is truncating the values: look at line 33.
What not use std::swap() instead of L36-38. Then you don't need temp.
http://www.cplusplus.com/reference/algorithm/swap/
If he (or she)’s going to use algorithms, might as well use std::sort().
... unless it's a requirement to write a sort.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <iomanip>
#include <algorithm>

int main() {
	constexpr size_t MaxGrades {5};

	double grades[MaxGrades] {};
	double total {};

	for (size_t i {}; i < MaxGrades; ++i) {
		std::cin >> grades[i];
		total += grades[i];
	}

	std::sort(grades, grades + MaxGrades);

	const auto avg_grade {total / MaxGrades};
	const auto med_grade {grades[MaxGrades / 2]};	// Correct if odd number of grades
	const auto min_grade {grades[0]};
	const auto max_grade {grades[MaxGrades - 1]};

	std::cout << std::fixed << std::setprecision(2)
		<< avg_grade << ' ' << med_grade << ' ' << min_grade << ' ' << max_grade << '\n';
}


The median for a list with an even size is the average of the two middle-indexed values.
If the standard library is being used, nth_element is ideal for this:
https://en.cppreference.com/w/cpp/algorithm/ranges/nth_element
It requires linear time.
Last edited on
Topic archived. No new replies allowed.