Hi i'm currently doing a homework(I know that you will not give me the answer nor do i want it). What I have to do is to count the total of positive/negative numbers, the total of numbers that are enter and the average of the numbers but it seems i have a problem with my loop (i don't know if I have use the good one or if I did not use it correctly )
thanks in advance
#include <iostream >
usingnamespace std;
int main() {
int number;
int totalNum =0, totalNeg=0, Max=0, Min=0;
double Moy=0;
cout<<"please enter numbers, enter <0> to finish";
cin>>number;
if (cin.fail()){
cout<<"what you have enter is invalid"<<endl;
cin.clear();
while (cin.get() !=0) {}
//while (number !=0) {} // something i have tried
cout<<"ok"; //to test if my prog enter in the while but it does not
totalNum ++;
if (number < 0)
totalNeg = totalNeg + number;
Moy=Moy+number;
cin>>number;
}
Moy = Moy/totalNum;
cout<<"moy = "<< Moy <<endl;
cout<<"total of the negative numbers = "<<totalNeg<<endl;
system("pause");
return 0;
First, there is no body in your loop. Your flow goes like this:
1 2 3 4 5 6 7 8 9
cin >> number;
if ( /* the user entered a number */ )
{
while( /* a condition is true */ ) {}
// some code
}
The {} there is the body of your loop. No matter the result of the conditions ( how many times the loop happens ), // some code will only happen once.
You might want it to be something more like this:
1 2 3 4 5 6 7 8 9 10 11
cin >> number;
if ( /* the user did not enter a number */ )
{
cout << "Not good, my friend\n";
return 0;
}
while ( /* the number is not zero */ )
{
// do your math and re-get the number
}
Second, cin.get() returns a character, and you are comparing it to an integer, specifically zero. While it is not impossible to enter the zero character into the keyboard, I would imagine you were meaning to do something like: while ( cin.get() != '0' )