View Full Version : Avg program in c
dukebound85
Oct 6, 2006, 02:54 AM
never mind i figured it out
this can be a wastelanded
YoNeX
Oct 6, 2006, 03:17 AM
#include <iostream>
using namespace std;
int main(){
int num;
int avg = 0;
int avg_count = 0;
do
{
cout << "Enter in a number to average or -1 to terminate: ";
cin >> num;
if(num > 0)
{
avg += num;
avg_count++;
}
}
while(num >0);
cout << "Your average is: " << avg / avg_count << endl;
return 0;
}
EDIT: Guess I posted this too late.
bousozoku
Oct 6, 2006, 03:20 AM
You should think about doing excellent programmes, not just average ones. ;)
dukebound85
Oct 6, 2006, 02:38 PM
#include <iostream>
using namespace std;
int main(){
int num;
int avg = 0;
int avg_count = 0;
do
{
cout << "Enter in a number to average or -1 to terminate: ";
cin >> num;
if(num > 0)
{
avg += num;
avg_count++;
}
}
while(num >0);
cout << "Your average is: " << avg / avg_count << endl;
return 0;
}
EDIT: Guess I posted this too late.
Good call. Always nice to see a different way to accomplish the same thing.
Haha yea only excellent programs here on out
what does the += do in your if function. thanks
balamw
Oct 6, 2006, 02:48 PM
what does the += do in your if function. thanks
avg += num;
is shorthand for
avg = avg + num;
B
YoNeX
Oct 6, 2006, 04:14 PM
Now, if you want to store each value, the best way is arrays.
It would be something like int avg_num[9999]; Then you just set the assign the number to each of the avg_num (i.e. avg_num[0] = 1; avg_num[1] = 5). But in this case, no real use for storing the values anyways.
In this case, I used vectors: http://www.cs.ucr.edu/~ttaing/gpa_calculator.php . Just a GPA calculator, but takes the same idea as averaging values and reading in string to determine the value. As you can see, I can make the code run more efficently, but I'm not too worried about that. There are numerous ways to solve your problem, right now, just worry about getting it right, then optimizing the code later.
vBulletin® v3.8.6, Copyright ©2000-2012, Jelsoft Enterprises Ltd.