I'm working on a program to ask an average of the users specified numbers and am wondering why this code won't work the way I want it to. What did I do wrong with this code? I really feel like I did everything cleanly...
#include <iostream>
#include <cstdlib>
#include <iomanip>
usingnamespace std;
int sumNum (int amount, int num, int sum, int average);
void displaySum (int sum, int average);
int main()
{
int amount = 0;
cout << "Insert the amount of numbers to be averaged." << endl;
cin >> amount;
int average = 0, sum = 0;
while (amount != 0)
{
for (int last = 0; last < amount; last++)
{
int num = 0;
cout << "Insert a value: " << endl;
cin >> num;
sumNum(amount, num, sum, average);
displaySum (sum, average);
}
}
system("pause");
return 0;
}
int sumNum (int amount, int num, int sum, int average)
{
sum = sum + num;
average = sum / amount;
return sum, average;
}
void displaySum (int sum, int average)
{
cout << "The sum is: " << sum << endl;
cout << "The average is : " << average << endl;
}
Well, one thing I'm noticing is that you're trying to return two values from a function at the same time. I can never understand why beginners seem to think that they can, or what makes them think that they can, but whatever.
Anyways, YOU CAN'T return two values at the same time, so you have to fix that. The code you've written is not syntactically illegal, which is why your compiler didn't complain, it's just doing something different from what you thought it did. I could explain what it's doing, but there's no point unless you're SUPER curious.
You don't need the while loop. Sum shall be incremented in main(), sumNum shall be named averageNum. Both averageNum() and displayNum() shall be outside the loop. Avoid System() call.
#include <iostream>
usingnamespace std;
int averageNum (int amount, int sum);
void displaySum (int sum, int average);
int main()
{
int amount = 0;
cout << "Insert the amount of numbers to be averaged." << endl;
cin >> amount;
int average = 0, sum = 0, num = 0;
for (int last = 0; last < amount; last++)
{
cout << "Insert a value: " << endl;
cin >> num;
sum+=num;
}
average = averageNum(amount, sum);
displaySum (sum, average);
system("pause");
return 0;
}
int averageNum (int amount, int sum)
{
return (sum / amount);
}
void displaySum (int sum, int average)
{
cout << "The sum is: " << sum << endl;
cout << "The average is : " << average << endl;
}
int sumNum (int amount, int num, static int &sum, int &average);
void displaySum (int sum, int average);
int main()
{
int amount = 0;
int average = 0, sum = 0;
int num;
do { cout << "Insert the amount of numbers to be averaged." << endl;
cin >> amount;
for (int last = 0; last < amount; last++)
{
cout << "Insert a value: " << endl;
cin >> num;
sumNum(amount, num, sum, average);