我是C ++的新手,当我遇到打嗝时正在尝试这个程序。这不是技术问题。程序运行得很好。
#include<iostream>
int main()
{
using namespace std;
int num1, num2;
char ch;
cout << "Enter the two integers: ";
cin >> num1 >> num2;
cout << "Choose one of the following arithmetic operators: " << endl;
cout << "+" << endl;
cout << "-" << endl;
cout << "*" << endl;
cout << "/" << endl;
cin >> ch;
if (ch == '+')
cout << "The sum of the two numbers is: " << num1 + num2 << endl;
if (ch == '-')
cout << num2 << " subtracted from " << num1 << " is " << num1 - num2 << endl;
if (ch == '*')
cout << "When multiplied: " << num1*num2 << endl;
if (ch == '/')
cout << num1 << " divided by " << num2 << " will be " << num1 / num2 << endl;
else
cout << "Wrong input. Try again.";
return 0;
}
现在问题就在于此。当满足if语句以及提供的计算时,输出还会显示else语句中的语句。 我尝试将else编辑为: -
else if(ch=!'+','-','*','/')
和
if(ch=!'+','-','*','/')
但它们似乎都没有用。在所有情况下,“错误的输入。再试一次。”以某种方式找到输出的方式。我哪里错了?
答案 0 :(得分:10)
您的整个结构必须是if
- else if
- else
,如下所示:
if(ch=='+')
cout<<"The sum of the two numbers is: "<<num1+num2<<endl;
else if(ch=='-')
cout<<num2<<" subtracted from "<<num1<<" is "<<num1-num2<<endl;
else if(ch=='*')
cout<<"When multiplied: "<<num1*num2<<endl;
else if(ch=='/')
cout<<num1<<" divided by "<<num2<<" will be "<<num1/num2<<endl;
else
cout<<"Wrong input. Try again.";
但这是最好的做事方式吗?可能不是。既然您只是在测试以查看ch
等于什么,那么您实际上可以使用另一个内置的C ++构造,即switch
语句:
switch (ch) {
case '+':
cout << "The sum of the two numbers is: " << num1+num2 << endl;
break;
case '-':
cout << num2 << " subtracted from " << num1 << " is " << num1-num2 << endl;
break;
case '*':
cout << "When multiplied: " << num1*num2 << endl;
break;
case '/':
cout << num1 << " divided by " << num2 << " will be " << num1/num2 << endl;
break;
default:
cout << "Wrong input. Try again." << endl;
break;
}
答案 1 :(得分:6)
在原始代码中,PATH
仅适用于最后一个PYTHONPATH
语句。你需要链接你的条件:
else
但是,您最好使用if
语句:
if(ch=='+')
cout<<"The sum of the two numbers is: "<<num1+num2<<endl;
else if(ch=='-')
cout<<num2<<" subtracted from "<<num1<<" is "<<num1-num2<<endl;
else if(ch=='*')
cout<<"When multiplied: "<<num1*num2<<endl;
else if(ch=='/')
cout<<num1<<" divided by "<<num2<<" will be "<<num1/num2<<endl;
else
cout<<"Wrong input. Try again.";
答案 2 :(得分:1)
else
不等于ch
时, /
部分将始终执行,因为else部分仅与if(ch=='/')
匹配。可能您想使用if else阶梯或转换案例。
答案 3 :(得分:0)
&#34; Else-statement&#34;与最后的&#34; if-statement&#34;相关联。因此,如果非最后一个if语句avaliates为true,那么最后一个将avaliate为false,这意味着对else语句的真实avaliation。您可以将if语句更改为&#34;否则,如果&#34; (不要使用第一个if语句)。