#include <iostream>
#include <cmath>
usingnamespace std;
float average(int*, int);
float median(int*, int);
int mode(int*, int);
int main()
{
int num;
float a;
int b, c;
cout << "Number of students surveyed: ";
cin >> num;
int *student;
student = newint[num];
for (int i = 0; i < num; i++)
{
cout << "Number of movies student number "<<i+1<<" saw: ";
cin >> student[i];
}
a = average(student, num);
b = median(student, num);
c = mode(student, num);
cout << "The average is "<<a<<endl;
cout << "The median is "<<b<<endl;
cout << "The mode is "<<c<<endl;
}
float median(int student[], int num)
{
int mid = num/2;
if ((num%2)==0)
{
return (student[mid-1]+student[mid])/2;
}
elsereturn student[mid];
}
float average(int student[], int num)
{
float avg;
float temp;
for (int i = 0; i < num; i++)
{
temp = temp + student[i];
}
avg = temp/num;
return avg;
}
int mode(int student[], int num)
{
int counter = 1;
int max = 0;
int mode = student[0];
for (int i = 0; i < num - 1; i++)
{
if ( student[i] == student[i+1] )
{
counter++;
if ( counter > max )
{
max = counter;
mode = student[i];
}
}
else
counter = 1;
}
return mode;
}
Number of students surveyed: 4
Number of movies student number 1 saw: 1
Number of movies student number 1 saw: 1
Number of movies student number 1 saw: 2
Number of movies student number 1 saw: 3
The average is 1.75
The median is 1
The mode is 1
I know it's supposed to be sorted first. I'm just confused in why the float is not returning decimal values.
In median you are only doing operations with integers, so by the time you return your result, it is still an integer, which is then converted to a float:
1 2 3 4 5 6 7 8
//An example:
float func() {
return 5/2; //these are both integers so you get a result of 2, which is then converted to a float
}
int main() {
float x = func(); //x is 2, not 2.5
}