Wednesday, January 13, 2016

Limbajul C/C++. Operatorul ternar versus if/else

Sigur ca pare doar un mic amuzament sa rezolvi o problema de decizie cu operatorul ternar, singurul din tot limbajul care functioneaza cu trei operanzi. Uneori insa, in virtutea conciziei, o astfel de optiune este justificata, dupa cum este justificat, ba chiar preferabil, din considerente de eficienta, sa faci atribuirea:

int x = 0;
while(x <= 10) {x += 1;} in loc de "x = x + 1;"

intrucat in al doilea caz x este evaluat de doua ori.

Enuntul de pe programmr.com:

"Take input of experience and age of a person.
If the person is experienced and his age is equal to or more than 35 the slary of the person is 6000. Otherwise, if the person is experienced and his age is equal to or more than 28 but less than 35, then the salary should be 4800.For experienced person below 28 yr of age the salary should be 3000 and for inexperienced person the salary should be 2000."


In cazul operatorului ternar unde c, a, b sunt variabile de un tip oarecare, ultimele doua preferabil initializate
c? a : b; 
c este evaluat boolean (true/false) si intreaga expresie primeste valoarea a (pentru true), respectiv b (pentru false), rezultatul putand fi atribuit unei variabile left-value.

Codul si printscreen-ul:

#include <iostream>    

using namespace std;    

int main()    
{    
   int salary, exp, age;    
   cout<<"\n Is the person experienced ? Enter 1 for yes, 0 for no : ";    
   cin>>exp;    
   cout<<"\n Enter age of the person : ";  
   cin>>age;  
   (exp == 0)? salary = 2000 : salary = (age >= 35)? 6000 : ((age >= 28)? 4800 : 3000);
   cout<<"\n The salary of the person is "<<salary;
   return 0;    
}    


Link-ul catre codul executabil.

No comments:

Post a Comment