C++ Calculator Skipping Else Statement

后端 未结 4 1017
伪装坚强ぢ
伪装坚强ぢ 2021-01-26 08:07

I was making a simple calculator in C++. However the program does not completely function the way it should. When run, the trig if statement executes fine, however, the basic ar

相关标签:
4条回答
  • Since you want to do something different for each trig function, you should just have a single if...else if...else if...else if...else chain. There is no need to nest the if statements as you have. In fact, it is probably less efficient because you check each condition twice.

    0 讨论(0)
  • 2021-01-26 08:28

    Change:

    if(function == "sin" || "cos" || "tan")
    

    into:

    if ((function == "sin") || (function == "cos") || (function == "tan"))
    

    What you have first calculates the expression "sin" || "cos" || "tan" and then tries to compare the string with that.

    But, in fact, it's not really necessary to have this two-step process. You can simply do something like this:

    if (function == "sin") {
        std::cin >> input;
        std::cout << "The sine is " << sin (input) << std::endl;
        system ("PAUSE");
    } else if (function == "cos") {
        std::cin >> input;
        std::cout << "The cosine is " << cos (input) << std::endl;
        system ("PAUSE");
    } else if (function == "tan") {
        std::cin >> input;
        std::cout << "The tangent is " << tan (input) << std::endl;
        system ("PAUSE");
    } else {
        // It's neither sin, cos nor tan if you get here.
    
        firstnumber = ::atof (function.c_str ());
    
        // and the rest of your stuff in here.
    }
    
    0 讨论(0)
  • 2021-01-26 08:29

    This line is wrong.

    if(function == "sin" || "cos" || "tan")
    

    It should be

    if((function == "sin") || (function == "cos") || (function == "tan"))
    

    Note that the check is actually meaningless because you already check for them each individually. You could tidy this up by doing this in a if, else if, else chain.

    0 讨论(0)
  • 2021-01-26 08:40

    You must write out each condition separately. The following line of code compiles but it doesn't do what you think:

    if (function == "sin" || "cos" || "tan")
    

    Change it to the following:

    if (function == "sin" || function == "cos" || function == "tan")
    
    0 讨论(0)
提交回复
热议问题