How to use a loop to find average of any dataset?

I'm writing a code to use linux redirection to input any dataset into my program, and then list which number is either abundant, deficient, or perfect.
abundant= sum of its factors are more than 2*n
deficient= sum of its factors are less than 2*n
perfect= sum of its factors are equal to 2*n

I need to find the average of the abundant inputs with two points to the right of the decimal. (ex, in the set, 24 and 18 are abundant numbers and their average is 21). The only thing I'm struggling with is using a for loop to count the abundant inputs so i can find their average.

At this point, when I run the program, it doesn't go through the entire dataset because of the for loop i used probably has an inefficient middle term, but I don't know what else to put.

My code:
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int n;
double average;
double abundant=0;
int sum=0;
int i=1;
cout << "Input" << setw(15)<< "Abundant" << setw(15) << "Deficient" << setw(16) << "Perfect" << endl;
cin >> n;
while (cin)
{
for (int initial=1; initial<=n; initial++)
if (n%initial==0)
{
sum = sum + initial;
}
if (sum > 2*n)
{
cout << n << setw(15)<< "x" << endl;
}
else
if (sum == 2*n)
{
cout << n << setw(50)<< "x" << endl;
}
else
if (sum < 2*n)
{
cout << n << setw(30)<< "x" << endl;
}
for (int i=1; sum > 2*n; i++)
{
abundant = abundant + n;
average = abundant / i;
}
sum = 0;
cin >>n;
}
cout << average << endl;
}
Last edited on
There is a confusion of logic here.

The only loop you should have is

1
2
3
4
5
  while (cin >> n)
  {
    sum += n;
    count += 1;
  }

Only after you have processed all data (and obtained a sum and number of data) do you have sufficient information to inform a conclusion of abundant, deficient, or perfect.

1
2
3
  if (sum > 2*count) ...
  else if ...
  else ...

Good luck!
Topic archived. No new replies allowed.