1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

cerr

Discussion in 'C' started by wdliming, Oct 16, 2010.

  1. wdliming

    wdliming New Member

    Joined:
    Sep 26, 2010
    Messages:
    28
    Likes Received:
    0
    Trophy Points:
    0
    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
     
    Last edited by a moderator: Oct 16, 2010
  2. jimblumberg

    jimblumberg New Member

    Joined:
    May 30, 2010
    Messages:
    120
    Likes Received:
    29
    Trophy Points:
    0
    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
     
  3. wdliming

    wdliming New Member

    Joined:
    Sep 26, 2010
    Messages:
    28
    Likes Received:
    0
    Trophy Points:
    0
    Thank you very much~~~
     

Share This Page