C++ Calculator Skipping Else Statement

后端 未结 4 1019
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  [愿得一人]
    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.
    }
    

提交回复
热议问题