#include <iostream>
usingnamespace std;
int num_nums; //number of numbers that the user wants to average
int num1;
int num2;
int num3;
int main()
{
cout << "How many numbers do you want to average: ";
cin >> num_nums;
cout << "Enter numbers here: ";
if (num_nums == 1) //if user wants to average 1 number, go here
{
cin >> num1;
cout << "The average is: " << num1;
}
elseif (num_nums == 2) //if user wants to average 2 numbers, go here
{
cin >> num1 >> num2;
cout << "The average is: " << (num1 + num2)/2;
}
elseif (num_nums == 3) //if user wants to average 3 numbers, go here
{
cin >> num1 >> num2 >> num3;
cout << "The average is: " << (num1 + num2 + num3)/3;
}
return 0;
}
This program will allow the user to chose an amount of numbers (up to 3) and get an average of the numbers that he inputs. I want to be able to do it to infinity, but I cannot figure out how to get cin >> "amount of num_nums the user selected"
Get number of numbers from user.
Then loop from i=0 to i=numberOfNUmbers-1
{
get next number
put it on end of vector
}
now sum vector and calculate average
I did it, and it worked! Thank you! But I have two quick questions.
1) I did not put sum=0 before, and it worked. Why did you put it? Is it necessary?
2) What is the difference between putting ++i and i++ (on the last part of the for loop). I am yet to understand that, and for this program, either gives me the correct result. Do you mind explaining that a little bit please?
I do not know where you put sum because I do not see your code. As for ++i and i++ then for fundamental types these expressions used in loops have no a difference.
It depends on where sum is declared. If it is declared before the main then there is no problem because variables with static storage class are initialized by zero. If it declared inside the main then the result is undefined.