Hello LegalWeasel,
Lines 7 - 11 define variables, but they all have a garbage value. "a" is defined as an "int" and on my computer the garbage value is usually "-858993460", but could be different. So "-858993460" + 1 = "-858993459" and in the end "answer" will never have a correct value.
Try:
1 2 3 4 5
|
int n{};
int i{}; // <--- Should be defined in the for loop.
int a{};
int answer{};
double num[100]{};
|
The empty {}s or "uniform initializer" will set the "int"s to zero and all the elements of the array to "0.0". It is always best to initialize your variables when defines. At the very least you know they will not contain a garbage value.
"double" is the preferred floating point type, but sometimes a "float" will work if the numbers are small.
Beyond that you will have to be more specific as to which line is causing the problem.
In this code:
1 2 3 4 5 6 7
|
for (i = 0; i < n; i++)
{
std::cout << i + 1 << ". Enter number: ";
std::cin >> i;
a += i;
}
|
"i" is the loop iterator, so on line line 4 when you enter a new value for "i" it throws the whole for loop off. You need a variable other than "i" unless you want to use "i" to access the array. Then it would be:
std::cin >>num[i];
and the next line would be:
a += num[i];
. You may want to consider:
std::cout << ". Enter number " << i +1 <<": ";
And the output would look like:
Enter the numbers of data: 3
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
The average is: 20
|
In line 31 I removed the "\n" from the end of "average and put it at the beginning of the string.
Andy.