1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

cerr

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

  1. wdliming

    wdliming New Member

    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

    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

    Thank you very much~~~
     

Share This Page