我必须制作一个程序,其中我应该以{{1}}和age
(无论该雇员是否有经验)作为雇员的用户输入,并打印出他/她的薪水。工资符合以下条件:
我编写了以下C ++程序:
experience
其中.
.
.
cout<<"The salary of the employee is Rs."<<(experience?sal1:2000); //LINE1
sal1=((age<=28)?3000:sal2);
sal2=((age<=35)?4800:6000);
return 0;
}
,age
,sal1
被声明为sal2
,int
被声明为experience
。
bool
,否则为experience=1
输入。
但是无论何时输入experience=0
和任何experience==1
,我都会得到意想不到的大整数结果,而当嵌套条件运算符时,代码将产生绝对完美的结果。(即,我复制{{1}的表达式}到LINE1中的 truth 表达式,并将age>28
的表达式复制到sal1
的表达式中)
请说明这两个代码之间的区别以及为什么在第一种情况下我会得到意外的结果。
注意:我已经使用gcc g ++编译器来编译我的代码。请说出是编译器,操作员的问题还是其他问题。
答案 0 :(得分:0)
我认为,如果改用普通的if ... else if ... else
,那么在编写和阅读时都更容易理解逻辑。
也许类似
int salary;
if (age <= 28)
{
salary = 3000;
}
else if (age > 28 && age <= 35)
{
salary = 4800;
}
else
{
// Age must be over 35 to come here
salary = 6000;
}
答案 1 :(得分:0)
不需要这么难读(写)的代码:
#include <iostream>
int calcSalary(int age, bool experience){
if (!experience)
return 2000;
if (age <= 28)
return 3000;
if (age <= 35)
return 4800;
return 6000;
}
int main(){
std::cout << "The salary of the employee is Rs." << calcSalary(36, false) << '\n';
return 0;
}
假设使用C ++ 11,则可以使用lambda:
#include <iostream>
int main(){
auto calcSalary = [](int age, bool experience){
if (!experience)
return 2000;
if (age <= 28)
return 3000;
if (age <= 35)
return 4800;
return 6000;
};
std::cout << "The salary of the employee is Rs." << calcSalary(36, false) << '\n';
// no return 0 need for C++11
}
答案 2 :(得分:0)
如果您确实要使用嵌套的三元运算符(例如,如果要在所有地方使用const
),则可以执行以下操作:
auto const salary = (!isExperienced) ? 2000 :
(age <= 28 ) ? 3000 :
(age <= 35 ) ? 4800 : 6000;
请记住,三元(?
)运算符的工作方式如下:
(conditional-statement) ? (if-true) : (if-false)
像示例中那样将它们链接在一起时,则会从上到下依次对其进行评估。因此,首先要测试isExperience
,如果员工有NOT
的经验,那么我们将其评估为2000
。从那里我们测试less than or equal to 28
,less than or equal to 35
。