编程中的条件判断与逻辑运算
1. 条件判断基础
在编程中,条件判断是非常重要的一部分。例如,当选择的直径不大于画布宽度的一半(即不大于 100 像素)时,会执行 else
子句,将绘制的圆的填充颜色设置为蓝色。以下是示例代码:
if (diameter > (width / 2) ) {
fill(255, 0, 0); // red
} else {
fill(0, 0, 255); // blue
}
这里使用了行末注释来明确选择的填充颜色,在 Processing 中,从两个斜杠 //
到行末的内容在运行程序时会被忽略。
2. if - else - if - else 语句
有时候,我们需要对多个互斥的条件进行测试,这时 if - else - if - else
语句就派上用场了。它的最简形式如下:
if (condition-1) {
Statement(s) to perform if condition-1 is true
} else if (condition-2) {
Statement(s) to perform if condition-2 is true
} else {
Statement(s) to perform if neither of the above conditions is true
}
<