Ternary Conditional Operator

0

I'm trying to translate an if and else condition into ternary, but conditions are compounded, ie I need to indicate more than one statement on the same line.

According to what I researched the same can be done using comma, but in the compiler it expects that they have more: and; I changed it according to the compiler's indication and it did not solve, I think it's something simple that I still can not find a suitable answer or fragments of answers that meet and this demand, follows the codes below.

class Fibonaci{

int calculaFibonaci(int n){
            /*if(n==1){
            fibonaci=1;
            fibonaci2=0;
            } else {

                fibonaci += fibonaci2;
                fibonaci2 = fibonaci- fibonaci2;
            }

            }*/

            fibonaci = (n==1)? fibonaci=1, fibonaci2=0 : fibonaci+=fibonaci2, fibonaci2 = fibonaci - fibonaci2;


            return fibonaci;
            }
}

OBS: Inside the comment is the condition if and else that works perfectly.

    
asked by anonymous 09.04.2018 / 15:13

1 answer

1

The use of the ternary in this case is incorrect. What you're trying to do is assign a value to the fibonaci variable. If you wanted to assign a value to this variable, you would only have to pass a single value in the ternary, and not create new assignments:

fibonaci = n==1 ? 1 : 2; // fibonaci seria ou 1 ou 2

In your case, to assign variables within the ternary, you would have to put the code in parentheses, and checking only if n==1 :

n==1 ?
(fibonaci=1, fibonaci2=0) :
(fibonaci += fibonaci2, fibonaci2 = fibonaci - fibonaci2);

The above ternary has the same effect as if commented /**/ in code.

    
09.04.2018 / 16:09