0

Hi, all
i have the assignment about program which reads in integers from cin until the user enters a non-integer (a character or EOF), then print out the average.
Its pretty simple assignment but i am kind of new.
So the following is my code and seems like have some problems.
So is there anybody could point out it?? Thanks

int main()
{
 int val=0,n=0;
 int ave;
 long int sum=0;
 

 cout<<"please enter the first interger..."<<endl;

 do
 {
  cin>>val;
  if(!cin)
  {
	  cin.clear();
	  cin.ignore(100);
	  cout<<"please enter an interger"<<endl;
  }
  else
  {
  sum+= val;
  n++;
  cout<<"please enter another interger..."<<endl;
  
  }
  }while(cin>>val);
 
 ave = sum/n;
 cout<<"the average is:"<<ave<<endl;

 system("pause");
}
4
Contributors
7
Replies
8
Views
8 Years
Discussion Span
Last Post by soroushc
0
while(cin>>val)
 {
  //cin>>val;
  if(cin.fail())
  {
	  cin.clear();
	  cin.ignore(100);
	  cout<<"please enter an interger"<<endl;
          continue;
  }
  else
  {
      sum+= val;
      n++;
      cout<<"please enter another interger..."<<endl;
  }
}

that is it..i guess..

0

Good guess, but not quite solving the problem
Both of your loops will keep you entering numbers forever

while( cin >> val )
{
  if( cin.fail( ) )
  {
      //do nothing, we've reached the quit criteria
  }
  else
  {
       //do the summation and counter increment
  }
}
0

The calculation is wrong!
think about ASCII CODE;)

#include<iostream>
using namespace std;
int main()
{
 int val=0,n=0;
 double ave;
 long  sum=0;
 

 cout<<"please enter the first interger..."<<endl;

 do
 {
  cin>>val;
  if(!cin)
  {
	  cin.clear();
	  cin.ignore(100);

  }
  else
  {
  sum+= val;
  ++n;
  cout<<"please enter another interger..."<<endl;
  cout<<"sum is in loop: "<<sum<<endl;
  }
  }while(cin>>val);
 
 cout<<"sum is: "<<sum;
 cout<<"n Is: "<<n<<endl;
 ave = sum/n;
 cout<<"the average is:"<<ave<<endl;

 system("pause");
}
0

The calculation is wrong!
think about ASCII CODE;)


Huh? ASCII has nothing to do with adding up some numbers.

Now, there is the case that the computed average will only be the integer value, as sum and n are both integers. This can be fixed by changing sum to a double, or typecasting one of the operands in the division to double.

0

if user inputs char the ascii would be different from integers!so by checking the ascii the program will come to know whether the input is char or not!!
btw I didn't say ASCII has to do with adding numbers:S,I meant for checking the input!

0

If the user enters some character that's not part of an integer, input halts at that point. It is not the case that if I hit 'a' on the keyboard that the ASCII value of 'a' will stored to the int variable val.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.