我在C ++中制作一个简单的计算器。但是程序并没有完全按照它应该的方式运行。运行时,trig if语句执行正常,但是,基本算术else语句不起作用。我已经确定代码没有执行else语句,并且想知道如何修复它。 else语句中的代码工作正常,因为我已经注释掉了if语句。帮助
这是我的代码:
#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;
}
答案 0 :(得分:2)
这条线错了。
if(function == "sin" || "cos" || "tan")
应该是
if((function == "sin") || (function == "cos") || (function == "tan"))
请注意,检查实际上没有意义,因为您已经分别检查了它们。您可以在if
,else if
,else
链中执行此操作来整理此操作。
答案 1 :(得分:0)
变化:
if(function == "sin" || "cos" || "tan")
成:
if ((function == "sin") || (function == "cos") || (function == "tan"))
您首先计算表达式"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 {
// It's neither sin, cos nor tan if you get here.
firstnumber = ::atof (function.c_str ());
// and the rest of your stuff in here.
}
答案 2 :(得分:0)
您必须分别写出每个条件。以下代码行编译,但它没有按您的想法执行:
if (function == "sin" || "cos" || "tan")
将其更改为以下内容:
if (function == "sin" || function == "cos" || function == "tan")
答案 3 :(得分:0)
由于您希望为每个trig函数执行不同的操作,因此您应该只有一个if...else if...else if...else if...else
链。没有必要像你一样嵌套if语句。事实上,它可能效率较低,因为您会检查每个条件两次。