Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a c++ program (using loops) that asks the user to type positive integers.

ID: 3811481 • Letter: W

Question

Write a c++ program (using loops) 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'.

I have a problem with this answer it does not give me the correct average. Can anyone help me to solve the problem

#include <iostream>
using namespace std;
int main()
{
int value, sum=0, count=0; // Variable declarations
float average;
while(value!=-1){
cout<<"Enter a value, enter -1 to stop entering: ";
cin>>value; // Input of values from user
if(value<0&& value!=-1)
cout<<" ERROR, enter any other value";
sum+=value;
count++;
}
average= sum/count;
if(average==0.0) // if the average is 0.0, display NO AVERAGE

cout<<"NO AVERAGE";

else
cout<<"average is:"<<average; // Display Average of entered values

}

1 include

Explanation / Answer

The below code will take the input from user and calculate the average of only positive integers

#include <iostream>
#include <math.h>

using namespace std;

int main()
{
int num;//input: user enters number
int sum = 1;
int count = 0;
cout << "Please enter the numbers (To exit enter -1)." << endl;

//start loop
do {
cin >> num;
if (num > 0 ){
sum = sum + num;
}
count+=1;
}
while (num!=-1);
float avg = sum/(count-1);
cout << avg << endl;
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote