
Dlaczego w pętli for nie mogę użyć operatora trójwarunkowego ?
Dyskutowane

Komentarze (3)
- Popularne
- Najnowsze
- Najstarsze
Musisz się zalogować, aby dodać komentarz
Guadalupe Gagnon
31 maja 2022, 14:28
You shouldn't be using the ternary operator for the purpose of this code. The correct way to do what you are trying to do is with and if() else statement. But to specifically help you with the proper use of the ternary operator.
You have multiple problems in the use of this operator. It is used to set one of two values based on a boolean expression. Defined as:
boolean expression ? value if true : value if false;
Your first problem is that you are using the equals = operator in the boolean expression part. The purpose of this operator is to set the value of the object on the left to the value on the right. That doesn't result in a true/false as the ternary requires and is trying to set the result of (tab[0] % 2) to 0. The correct operator you need is going to be the equality operator, double equals ==, which checks if the value on the left equals the value on the right.
The next problem is after the question mark ? you need values, but in the code you shared there are expressions. As I stated the ternary operator is used only to set a value, not to process code. So the expressions:
parzyste += tab[i] and niePryste += tab[i]
are illegal to use with the ternary.
So. The code that you are looking for, to do what you are trying to do, is:
This allows the execution of expressions.
Now one more thing. If this is the task where you need to count the residents on each side of the street then your solve is going to fail. The number at each index (that you input) represents the residents at each address. The code you shared checks if the number of residents at a particular address is odd or even, but you should be checking if the address itself is odd or even.
+1
Guadalupe Gagnon
31 maja 2022, 14:33
See my comment on the English task page:
Streets and Houses
0
Mateusz
31 maja 2022, 16:28
You explained in great detail. I understand that a triple operator is for simple tasks where he has to return something and I expect too much from him. Hope I understand well. Thank you :)
0