Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   cerr (http://www.go4expert.com/forums/cerr-t23588/)

wdliming 16Oct2010 19:59

cerr
 
A example about cerr:
Code:

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
 float a,b,c,disc;
 cout<<"please input three numbers between 0~65536:a,b,c:" << endl;
 while(1)
 {
  cin>>a>>b>>c;
  if (a==0)
  {
  cerr << "a is equal to zero,error!" << "\n" << "Please input again!" <<endl;
  }
  else if(a>65536||a>65536||c>65536)
  {
  cerr << "a or b or c is too big,error!" << "\n" << "Please input again!" <<endl;
  }
  else if ((disc=b*b-4*a*c)<0)
  {
  cerr<<"disc=b*b-4*a*c<0"<< "\n" << "Please input again!" <<endl;
  }
  else
  {
  cout<<"x1="<<(-b+sqrt(disc))/(2*a)<<endl;
  cout<<"x2="<<(-b-sqrt(disc))/(2*a)<<endl;
  }
 }
 return 0;
}

welcome to give some advices

jimblumberg 16Oct2010 20:57

Re: cerr
 
Use code blocks "[code] [ /code]"

Code:

else if ((disc=b*b-4*a*c)<0)
Use parenthesis when using addition/subtraction and multiplication/division.

Code:

else if ((disc=b*(b-4)*a*c)<0)

Code:

else if(a>65536||a>65536||c>65536)
Your variable b is not checked.
Don't use "magic" numbers (65536). Instead use a constant.

Code:

const int MAX_INT 65536; // before any functions or in global scope.

else if(a>MAX_INT || b>MAX_INT || c>MAX_INT)

This way if the maximum changes you only have to change it in one place. Plus a descriptive name will be understood when looking at the program in the distant future.

Jim

wdliming 20Oct2010 05:59

Re: cerr
 
Thank you very much~~~


All times are GMT +5.5. The time now is 23:42.