三元运算符中的条件不会引起任何变化 [英] Condition in ternary operator doesn't cause any change

查看:130
本文介绍了三元运算符中的条件不会引起任何变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码示例:

for $i(1..100){
   if ($i%15==0){$s="Divisible by 15"}
   elsif($i%5==0){$s="Divisible by 5"}
   else {$i%3==0 ? $s="Divisible by 3" : $s=$i};
   print $s."\n"}

这将显示部分正确的结果,如果一个数字可被3整除,它将显示数字"而不是可被3整除".

This displays partial correct results, if a number if divisible by 3, it displays the "number" and not "Divisible by 3".

输出示例:

1
2
3
4
Divisible by 5
6
7
8
9
Divisible by 5

PS:我必须以最小编号编写此代码.可能的字符数. (代码如此缓慢的原因)

PS: I have to write this code in the minimum no. of characters possible. (The reason why the code is so sluggish)

推荐答案

三元组?:具有比分配的优先级更高.使用括号将其解决:

The ternary ?: has higher precedence than assignment. Use parens to sort that out:

for my $i (1 .. 100) {
   my $s = "Divisible by ";
     $i%15==0 ? ($s .= 15)
   : $i%5==0  ? ($s .= 5)
   : $i%3==0  ? ($s .= 3)
   :            ($s  =$i);
   print "$s\n";
}

输出:

1
2
Divisible by 3
4
Divisible by 5
Divisible by 3
7
8
Divisible by 3
Divisible by 5

这篇关于三元运算符中的条件不会引起任何变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆