I'm still stuck on this one question, can someone help me with this?

4.) Write a program that asks the user to type positive integers. When the user types a negative value the program writes ERROR and asks for another value. When the user types -1 that means that the last value has been typed and the program must write the average of the positive integers. If the number of typed values is zero the program writes 'NO AVERAGE'.

This is the code that I came up with, and I do not know how to add the no average statement, also when I try to take the average it comes out as a decimal. Like I typed all 8's and the average came out as 6.3 something with about 5 decimal places. Thank you for the help in advance.

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main(){
    int number, count = 0;
    float sum, average;

    cout<<"Enter a Positive Integer: ";
    cin>>number;
    while(number!=-1){

        if(number>=1){
            cout<<"Enter a Positive Integer: ";
            cin>>number;
            sum+=number;
            count++;
        }
        else{
            cout<<"ERROR!\n"<<"Enter a Positive Integer: ";
            cin>>number;
        }
        if(number==-1){
        average=sum/count;
        cout<<"The Average of the Positive Integers is: "<< average<<endl;
    }
}
}

Recommended Answers

All 2 Replies

If the number of typed values is zero the program writes 'NO AVERAGE'.

After line 25 you would have a test for what count is. Not using the code style since this is not code:
if count > 0 then (what's on 26 and 27)
else no average.

commented: For some reason my average keeps coming out incorrect. +0

" I do not know how to add the no average statement " is what I addressed.

As to the wrong answer, test your code with a cout of what the values are at the time of count and sum.
Be aware you did not initialize sum so in some compilers that could be a random number. As to average, no need to initialize.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.