Data Structures and Algorithms Discussion Board
September 10, 2010, 02:36:52 PM *
Welcome, Guest. Please login or register.
Login with username, password and session length
News: Looking for a reliable webhosting provider? Read HostGator review to find 7 arguments in support of HostGator.
 
   Home   Help Search Login Register  
Pages: [1]
  Print  
Author Topic: A C++ Program  (Read 2352 times)
chichi
Newbie
*

Rating: 0
Offline Offline

Posts: 7


« on: March 15, 2009, 01:02:43 PM »

1. Write a C++ program using while (cin>>x) to get several integer numbers and calculate the average.
Logged
Denis
Newbie
*

Rating: 0
Offline Offline

Posts: 21


« Reply #1 on: March 15, 2009, 01:55:25 PM »

Try this:

Code:
#include <iostream>
using namespace std;

int main()
{
int i = 0;
int sum = 0;
int x;
while (cin >> x)
{
sum += x;
i++;
}
if (i != 0)
cout << "Average: " << (double)sum / i << endl;
else
cout << "Average: 0" << endl;
system("PAUSE");
}

Read more here: C++ Notes: Idiom - cin loop
Logged
chichi
Newbie
*

Rating: 0
Offline Offline

Posts: 7


« Reply #2 on: March 22, 2009, 07:39:45 AM »

Denis

The output of the program is blank.
Logged
Denis
Newbie
*

Rating: 0
Offline Offline

Posts: 21


« Reply #3 on: March 22, 2009, 12:40:55 PM »

It's not. Just enter integers and, then, enter a char:

1
2
3
4
5
x

It'll calculate average.
Logged
chichi
Newbie
*

Rating: 0
Offline Offline

Posts: 7


« Reply #4 on: March 24, 2009, 10:17:35 AM »

Thanks Denis.
I have to write a C++ program using while (cin>>x) to get several float numbers, calculate the average and display the result on the screen. Use setprecision to display two digits after decimal point.
« Last Edit: March 24, 2009, 11:50:27 AM by SiteAdmin » Logged
Denis
Newbie
*

Rating: 0
Offline Offline

Posts: 21


« Reply #5 on: March 24, 2009, 11:54:44 AM »

Try this code:

Code:
#include <iostream>
using namespace std;

int main()
{
int i = 0;
float sum = 0;
float x;
cout << "Enter numbers, type 'x' to stop: " << endl;
while (cin >> x)
{
sum += x;
i++;
}
cout.precision(2);
if (i != 0)
cout << "Average: " << fixed << (sum / i) << endl;
else
cout << "Average: 0" << endl;
system("PAUSE");
}

More about format flags here: format flags (streams, C++)
Logged
Algolist.net Editor
Administrator
Newbie
*****

Rating: 0
Offline Offline

Posts: 8


« Reply #6 on: March 31, 2009, 03:29:18 AM »

Topic has been split, see Program, C++.
« Last Edit: November 21, 2009, 04:22:03 AM by Algolist.net Editor » Logged
Pages: [1]
  Print  
 
Jump to:  

 
Partners Ads        Skater shoes store sold online