When I try to find the median of an even amount of numbers, the decimal is being cut off of the answer. I'm sure I'm just overlooking something simple. Any help would be much appreciated.
// Unit 9 modularized.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<string>
#include <iomanip>
usingnamespace std;
// Declare functions.
int askStudents();
int* askMovies(int getStudents);
int* sortMovies(int* askMovies);
int getMedian(int getStudents, int* setMovies);
//Declare variables.
int getStudents;
int* setMovies;
int main()
{
getStudents = askStudents();
setMovies = askMovies(getStudents);
sortMovies(setMovies);
getMedian(getStudents, setMovies);
return 0;
}
int askStudents()
{
cout << "How many students were surveyed? ";
cin >> getStudents;
while (getStudents < 0)
{
cout << "Please enter a non-negative number: ";
cin >> getStudents;
}
return getStudents;
}
int* askMovies(int getStudents)
{
// Creating array "setMovies" with size of getStudents using pointer.
int *setMovies;
setMovies = newint[getStudents];
// Storing the amount of movies each student watched into setMovies array.
for (int i = 0; i < getStudents; i++)
{
cout << "How many movies did each student watch: ";
cin >> setMovies[i];
while (setMovies[i] < 0)
{
cout << "Please enter a non-negative number: ";
cin >> setMovies[i];
}
}
// Printint setMovies for test
for (int i = 0; i < getStudents; i++)
cout << setMovies[i];
cout << "\n";
return setMovies;
}
int* sortMovies(int* setMovies)
{
for (int i = 0; i < getStudents; i++)
{
for (int j = i + 1; j <getStudents; j++)
{
if (setMovies[i]>setMovies[j])
{
int temp = setMovies[i];
setMovies[i] = setMovies[j];
setMovies[j] = temp;
}
}
}
for (int i = 0; i < getStudents; i++)
cout << setMovies[i];
cout << "\n";
return setMovies;
}
int getMedian(int getStudents, int* setMovies)
{
float median;
if (getStudents % 2 == 0)
{
median = (setMovies[(getStudents / 2) - 1] + setMovies[(getStudents / 2)]) / 2;
cout << "The median is: " << median << endl;
}
else
{
median = setMovies[(getStudents / 2)];
cout << "The median is: " << median << endl;
}
return median;
}
Anyone have a real world example where you would want to do this? Because there is a real world example of why you shouldn't...
If you're trying to be mathematically rigid, returning a float is already blowing it because you're reporting precision that isn't in the original data.
Yes, watching half a movie is actually a thing.. for a variety of reasons. But the data is rounded to integers.
So why report the median with false precision? That's flawed math.
Should work for odd or even numbers (and relies on the appropriate integer division).
A mean is routinely accepted as a float/double; why not then the median?
Rounding to int would introduce bias, which is one thing statistics tries to avoid.