Ternary conditional operator

Asked

Viewed 316 times

0

I am trying to translate a condition of if and Else in ternary, however the conditions are composed, ie, need to indicate more than one instruction in the same line.

According to what I researched it can be executed using comma, but in the compiler it expects you to have more : e ; I changed according to the indication of the compiler and did not solve, I believe to be something simple that I have not yet been able to locate an adequate answer or fragments of answers that meet and this demand, follows below the codes.

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 this the condition if and else that works perfectly.

  • 2

    Of curiosity, is this exercise? Because in practice it makes no sense to use ternary for this.

  • 2

    No one was curious to know what language it is? You have to add the tag. It looks like Java.

  • Yes it is java is an exercise, which consists basically in creating a method that makes the calculus fibonaci using the ternary, I was in doubt more precisely in the part where it speaks (expression) ? codigo1(true) : codigo2(false), inside the code I believe it would be the same thing I would put inside of{}, so the doubt is can I use more than one command per linah separating by comma? how much the java tag I n have merit yet to put the rsrs tag

1 answer

1

The use of the ternary in this case is incorrect. What you are trying to do is assign a value to the variable fibonaci. If you wanted to assign a value to that variable, you would only have to pass a unique 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 just check if n==1:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.