Hey guys, so Im trying to write a program that takes the average of up to 15 numbers and find the average. Ive been able to get the loop that finds the average to work. But when i try and have it so a keyword will exit the loop and find the average early. I run into real problems. Please Help!
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
usingnamespace std;
int main()
{
int i = 0;
int total = 0;
constint sizeofarray = 15;
float numbers[sizeofarray];
string end = "";
cout << "Please enter up to 15 numbers" << endl;
cout << "You can stop at anytime by typing 'done'" << endl;
cout << "Please enter a number: ";
for (int i = 0; i < sizeofarray; i++) {
cout << "Please enter another number, or say done: ";
cin >> end[i];
total += numbers[i];
while (end != "done" || i < 15) {
cout << "while loop enter number: ";
cin >> end[i];
if (end != "done") {
numbers[i] = atoi(end.c_str());
}
else {
cout << "The average is " << (float)total / sizeofarray << endl;
return 0;
}
}
cout << "The average is " << (float)total / sizeofarray << endl;
}
return 0;
}
line 22,27: You don't want a subscript here. std::string overloads the [] operator so this refers to the 1st, then the 2nd, then the 3rd, etc. character of the string as i increments.
line 25: You have the wrong operator here. You want &&, not ||. With ||, if end == "done" and i is < 15, your loop will continue.
Line 33,37: If you enter "done" early, your average is going to be wrong since you are dividing by 15, not the number of entries in the array.
Ok, I just found out that it dosnt. but Im not sure why that dosnt work. Because isnt 'i' keeping track of how many numbers have been entered? or am I just way of
At line 37, i has gone out of scope, so you don't know how many values were actually entered.
I would replace lines 33-34 with a break statement to end the loop, but you're still going to have to keep a separate counter.
It's also not necessary that numbers be an array unless that was a requirement of your assignment. Once you've added the number to the total, you're done with it.
I'm not sure what you mean 'i has gone out of scope'
i is defined at line 20. It is a local variable that exists only within the scope of the for loop. At line 36, the for loop ends and i goes out of scope.
If you were to attempt to use i at line 37, the compiler would tell you that i is undefined.