Display the sum and the average of the numbers in a loop.

//Write a c++ program that will input double numbers for the user in a loop
// until the average of the numbers is less than 10. When the loop ends
// display the sum and the average of the numbers.

My try to solve the question failed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 #include<iostream>
using namespace std;
int main()
{
 int a, b, sum=0, i;
 double avg=10.0;
 cout<<"Enter a number: ";
 cin>>a>>b;
 while (avg>=10.0)
 {

 sum = sum+a+b;
 avg= sum/i;
 i++;
 }
 cout<<"sum ="<<sum<<endl;
 cout<<"avg = "<<avg;
    return 0;
}
Last edited on
input double numbers

You read only two integers.

until the average of the numbers is less than 10.

Average is computed from the input. The average of 0 values is not 10.0.

int sum=0, i;
The i is undefined. It could be anything. It could be even 0. division by 0 is not ok.

avg= sum/i;
sum is int. i is int. int/int produces int. No fraction.

1
2
3
4
5
6
7
8
9
10
double value {};
double sum {};
size_t count {};
double avg {};
bool next {true};
while ( next && std::cin >> value ) {
  // compute sum, avg, count

  next = ( 10.0 <= avg );
}
could you please write it in a simpler way? im still at the start of learning c++
/Write a c++ program that will input double number


Do that bit first. Get that bit correct. Show us.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
using namespace std;
int main()
{
 int i;
 double a, b, avg=10.0, sum=0;
cout<<"Enter a number: ";
 cin>>a>>b;
 while (avg>=10.0)
 {

 sum = sum+a+b;
 avg= sum/i;
 i++;
 }
 cout<<"sum ="<<sum<<endl;
 cout<<"avg = "<<avg;
    return 0;
}
You still haven't initialised i. Presumably, int i = 1;

Why do you ask for ONE number and then enter TWO? The average is going to be wrong.
This Is According To Your Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
using namespace std;
int main()
{
 int i=2;
 double a, b, avg=10.0, sum=0;
cout<<"Enter a number: ";
 cin>>a>>b;
 while (avg>=10.0)
 {

 sum = a+b;
 avg= sum/i;
 }
 cout<<"sum ="<<sum<<endl;
 cout<<"avg = "<<avg;
    return 0;
}

BUT I THINK IT COULD BE SIMPLY WRITTEN AS FOLLOWING:
1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
using namespace std;
int main()
{
 double a, b, avg,sum=0;
cout<<"Enter two numbers: ";
 cin>>a>>b;
 sum = a+b;
 avg= sum/2;
 cout<<"sum ="<<sum<<endl;
 cout<<"avg = "<<avg;
}
He/she explicitly explicitly says "in a loop", @Abdullah Samo.

However, it is just plausible @mim97 has mis-translated the problem. @mim97, do you mean
(1) You keep entering a "double" (i.e. ONE floating-point number) until the average of all entered so far is less than 10?
OR DO YOU MEAN
(2) You keep entering TWO numbers until the average OF THOSE TWO NUMBERS is less than 10?

Your current code slightly favours the former, but who knows.
Last edited on
Topic archived. No new replies allowed.