Positive numbers and avg

Write your question here.
Enter any positive numbers. Loop stops when there is a negative number. Output the average of the numbers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;
main ()
{
int n, num, avg; //n is for amount of numbers

while (n > 0) //Positive numb
{
		cout << "Enter numbers " << endl;
		cin >> num;
		
		if (num > 0)
			avg += num;
		else
			n++;
		
		cout << "Average is" << avg/n << endl;
}

return 0;
}

Last edited on
What is your question, what problems are you having?

First problem I see is that your while condition is (n > 0), but you never initialize n, so your program has undefined behavior.
Likewise for avg: avg += num;, you're incrementing a junk value because avg has not been assigned a value. You probably want avg to initially be 0 (avg = 0).

You need to assign a value to n, ex: n = 3;
Last edited on
My first question is how can I stop my loop when it sees a negative number. I try plugging in negative numbers and it didn't stop the loop. The second question is when I try to find the average amount of number. When i run it, it finds the average of each number. Ex: I type 1 2 3 4. The output of average is -1 0 1 2

A few issues then, you have two variables: n, and num. What job is each variable supposed to be doing?
It looks like n is supposed to keep track of the number of numbers you have entered, and num is the current number being entered. The "else n++" part of your code I don't think is necessary, I think it would make more sense to do
1
2
3
4
5
6
cin >> n;
if (num > 0)
{
    avg += num;
    n++;
}


with your while condition being while (num > 0)

Also, don't have the cout << "Average is" << ... line inside the loop: Place that after the loop ends.

And don't forget to initialize your variables before your loop!
Initialize n to be 0, num to some positive number, and initialize avg to be 0!

One more thing:
avg/n is doing integer division: This cuts off any decimal places that would happen.
Try seeing if your results are different if you do this: "Average is " << static_cast<double>(avg)/n
This makes floating-point division happen instead.

Edit: += num instead of += n.
Edit 2: Some other typos I made, sorry, you probably want to re-read my post
Last edited on
Topic archived. No new replies allowed.