Mac Avg program in c

Status
Not open for further replies.

YoNeX

macrumors regular
Apr 29, 2005
141
0
#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.
 

dukebound85

macrumors P6
Original poster
Jul 17, 2005
18,105
1,281
5045 feet above sea level
YoNeX said:
#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
 

YoNeX

macrumors regular
Apr 29, 2005
141
0
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.
 

Status
Not open for further replies.