Hello, I feel like I am super close but I can not figure out why my C++ code it not displaying the proper medium. Thank you!
Here is an example of the output:
Input : a[] = {1, 3, 4, 2, 6, 5, 8, 7}
Output : Mean = 4.5
Median = 4.5
Code so far:
#include <iostream>
using namespace std;
int main()
{
int a[100];
int n,i,sum=0;
float mean, medium;
//read array size
// read array
cout<<"Enter array size: ";
cin>>n;
//loop for reading
i=0;
while (i<=n-1)
{
cin>>a[i];
++i;
}
for (i=0;i<n;i++)
{
sum +=a[i];
}
mean=sum/(float)n;
cout<<"The mean is: "<<mean<<endl;
//sort the array
int temp, j;
for(int i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(a[i]<a[j])
{
temp=a[i];
//swap
}
//even num
if(n%2==0)
{
medium = (a[n-1/2]+a[n/2])/2;
}
else
{
medium=a[n/2];
}
cout<<"The medium is: "<<medium<<endl;
return 0;
}
Below is the corrected code. Now mean and median is calculating correctly.
#include <iostream>
using namespace std;
int main()
{
int a[100];
int n, i, sum = 0;
float mean, medium;
//read array size
// read array
cout << "Enter array size: ";
cin >> n;
//loop for reading
i = 0;
while (i <= n - 1)
{
cin >> a[i];
++i;
}
for (i = 0; i < n; i++)
{
sum += a[i];
}
mean = sum / (float)n;
cout << "The mean is: " << mean << endl;
//sort the array
int temp, j;
//Sort array using single for loop
for (int j = 0; j < n - 1; j++)
{
// check 2 similtaneous elements of the array
if (a[j] > a[j + 1])
{
// Swapping the elements.
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
// updating the value of j = -1
// so after getting updated for j++
// in the loop it becomes 0 and
// the loop begins from the start.
j = -1;
}
}
//even num
if (n % 2 == 0)
{
medium = (double)(a[(n - 1) / 2] + a[n / 2]) / 2;
}
else
{
medium = (double)a[n / 2];
}
cout << "The medium is: " << medium << endl;
return 0;
}
In existing code array sort was not working properly. Corrected code to sort the array. Also used double casting for calculated median Now mean and median is calculating correctly. Below is the output
Get Answers For Free
Most questions answered within 1 hours.