Need Answer by TODAY. Worked for hours.

Write the appropriate loop that will ask the user to enter a positive number and add each number entered to a running total (accumulator). The loop should end when the user enters a negative number. After the loop ends, print the average of the numbers that were input by the user. Do not write an entire program, simply declare and initialize the needed variables, write the loop header, the loop body and the output statement. Only calculate and print the average if the sum is not equal to zero.

I am totally stuck on this problem. I need an answer by today, and I have already tried to work on it for hours. I've been able to get to the point where the average is calculated, but it never works because it just displays random garbage.

How do you get the average number from numbers entered into an array when the maximum/limit of the array is indefinate?
Show me your code. I don't wanna do your homework.

Also need help:
Write the code to open a file whose physical name is “mycosts.txt”
Then write the code to read every number in this file and print it to the screen.
You do not know how many numbers are in the file, but you know there are only
numbers in the file.
Be sure to close the file when you are done.
/********************************************************************************************************


Purpose: Asks the user to enter a positive number. Adds each number to a running total. Ends when the user
enters a negative number. Only calculates and prints the average if the sum is not equal to zero.

*********************************************************************************************************/


#include <iostream>
using namespace std;

int main()
{
// Declare variables.
int count = 1;
int numberOfNumbers;
int userInput;
int numberA;
int numberB;
int numberC;
int array[count];
int sum;
int avg = 0;

//Output:
cout << "Please enter a positive number. Enter a negative number to quit the program.\n" << count << ": ";
cin >> userInput;
if (userInput >= 0)
{
{
cout << "\n" << (count += 1) << ": ";
cin >> userInput;
array[count] = userInput;
sum += array[count];
numberOfNumbers = count;
avg = sum/numberOfNumbers;
} while (userInput >= 0);
}
else if (userInput < 0)
{
cout << "The average of the positive numbers entered is " << avg;
}
else if (sum = 0)
{
cout << "The sum is 0. No average to be calculated.";
}
cout << "Done.";
return 0;
}

I would not store all input integer to an array. Just keep track of total and how many numbers are typed. Something like

1
2
3
4
5
6
7
8
9
10
total = 0
count = 0

while (input > 0) {
   total += input
   ++count
}

if (count != 0)
   print ( total / count )


this is just pseudo code but should be the idea/
Last edited on
Topic archived. No new replies allowed.