C ++计算器跳过其他语句 [英] C++ Calculator Skipping Else Statement
问题描述
我当时用C ++制作了一个简单的计算器.但是,该程序不能完全按照应有的方式运行.运行时,trig if语句执行良好,但是基本的算术else语句不起作用.我已经确定该代码未执行else语句,并且想知道如何解决它.else语句中的代码可以正常工作,因为我已经注释掉了if语句.帮助吗?
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 arithmetic else statement doesn't work. I have determined that the code is not executing the else statement and was wondering how to fix it. The code inside the else statement works fine, as I have commented out the if statement. Help?
这是我的代码:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cmath>
int main()
{
double input = 0;
double firstnumber = 0;
double secondnumber = 0;
std::string function;
std::string operation;
std::cout << "Enter your calculation: ";
std::cin >> function;
if(function == "sin" || "cos" || "tan")
{
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
{
firstnumber = ::atof(function.c_str());
std::cin >> operation;
std::cin >> secondnumber;
double valueadd = firstnumber + secondnumber;
double valuesubtract = firstnumber - secondnumber;
double valuemultiply = firstnumber * secondnumber;
double valuedivide = firstnumber / secondnumber;
if(operation == "+")
{
std::cout << " = " << valueadd << std::endl;
system("PAUSE");
}
else if(operation == "-")
{
std::cout << " = " << valuesubtract << std::endl;
system("PAUSE");
}
else if(function == "*")
{
std::cout << " = " << valuemultiply << std::endl;
system("PAUSE");
}
else if(function == "/")
{
std::cout << " = " << valuedivide << std::endl;
system("PAUSE");
}
else
{
std::cout << "Error" << std::endl;
return 0;
}
}
return 0;
}
推荐答案
此行是错误的.
if(function == "sin" || "cos" || "tan")
应该是
if((function == "sin") || (function == "cos") || (function == "tan"))
请注意,检查实际上是没有意义的,因为您已经分别检查了它们.您可以通过在 if
, else if
, else
链中进行此操作来整理.
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.
这篇关于C ++计算器跳过其他语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!