-2

I have a couple of issues that i need to fix.This program finds the average of a number desired by the user.For example if they put in 3 and then 1,2,3 then the average is 2. First of all my program is supposed to stop if zero is inputed. so if i put in 3 as the number of integers that will be averaged, and then i type 1,2,0 it should stop and not calculate the average. Also, i need to account for negative numbers.

#include <iostream>
using namespace std;
double avgVal(int, int);
int main()
{
    int amountOfCases;
    cin >> amountOfCases;
    int * numbers = new int[amountOfCases];
    int sum = 0;
    while(numbers !=0)
    {
    for (int i = 0; i<amountOfCases; i++)
    {
        cin >> numbers[i];
        sum = sum + numbers[i];
    }


    cout<<avgVal(sum, amountOfCases)<<endl;
    delete[] numbers;
    }
    system("pause");
    return 0;
}

double avgVal(int sum, int amountOfCases)
{
    return sum / (double)amountOfCases;
}
Ilian
  • 5,113
  • 1
  • 32
  • 41
jimm bo
  • 3
  • 4

1 Answers1

0

Not sure what you thought of when adding the while loop. It is not necessary, given the problem you are trying to solve.

Change the lines:

while(numbers !=0)
{
for (int i = 0; i<amountOfCases; i++)
{
    cin >> numbers[i];
    sum = sum + numbers[i];
}

cout<<avgVal(sum, amountOfCases)<<endl;
delete[] numbers;
}

to

for (int i = 0; i<amountOfCases; i++)
{
   cin >> numbers[i];
   if ( numbers[i] == 0 )
   {
      exit(1); // Exit with a non-zero status, indicating failure.
   }
   sum = sum + numbers[i];
}

cout<<avgVal(sum, amountOfCases)<<endl;
delete[] numbers;
R Sahu
  • 204,454
  • 14
  • 159
  • 270