Форум » C/C++ для начинающих (C/C++ for beginners) » Basic c++ for loop help » Ответить

Basic c++ for loop help

fujin009: #include <iostream> using namespace std; int main() { { int i=0; float input; for (;input!=-1;) { cout<<"Enter a Grade or -1 to exit: "; cin>> input; if (input!=-1) i++; } { cout<<"Number of Grades Entered: "<<i<<endl; cout<<"Grade Average: "<<input/i; } } return 0; } What I'm making is a for loop average calculator. There is no limit on how many grades I can put. So basically once I enter a bunch of grades and input -1, I will get the average. The problem is whenever I try to input -1 it replaces the "input"value which ends up with it averaging -1. I searched google and everything I just can't find a accurate answer. The output should be something like this: Enter a Grade or -1 to exit: 86.5 Enter a Grade or -1 to exit: 92.6 Enter a Grade or -1 to exit: 84.7 Enter a Grade or -1 to exit: 83.8 Enter a Grade or -1 to exit: -1 Number of Grades Entered: 4 Grade Average: 86.9

Ответов - 1

Сыроежка: first of all why did you mark your post as for reading only by administrator? I do not see that it is necessary. So would you like to remove this mark from your post? As for the code then these statements float input; for (;input!=-1;) are already wrong because variable input was not initialized. So it has an arbitrary value that can be equal to for example -1. The valid code can look the following way #include <iostream> using namespace std; int main() { const float sentinel = -1.0f; int i = 0; float input; float sum = 0.0f; do { cout << "Enter a Grade or " << sentinel << " to exit: "; cin>> input; if ( input != sentinel ) { sum += input; i++; } } while ( input != sentinel ); cout << "Number of Grades Entered: " << i << endl; if ( i != 0 ) cout << "Grade Average: " << sum / i << endl; return 0; }



полная версия страницы