你能通过if / else语句声明一个变量吗?
int num1;
int num2;
int num3;
if (num1 <= num2){
num3 = (num1-num2);
}else{
num3 = (num2-num1);
}
答案 0 :(得分:2)
您可以在if / else:
中分配变量self.completion(self);
您还可以在if / else中声明变量,但之后不会显示。
int num1 = 2;
int num2 = 3;
int num3; // This is a declaration
if (num1 <= num2){
num3 = (num1-num2); // This is an assignment
}else{
num3 = (num2-num1); // This is an assignment
}
// We can use num3 here
如果在if / else中分配变量,请确保保证分配变量。
int num1 = 2;
int num2 = 3;
if (num1 <= num2){
int num3 = (num1-num2); // This is a declaration and assignment in one.
}else{
int num3 = (num2-num1); // So is this
}
// We can't use num3 here.
使用条件运算符(也称为三元运算符)而不是在if / else中分配
通常更好int num1 = 2;
int num2 = 3;
int num3;
if (num1 <= num2){
num3 = (num1-num2);
}else if (num1 == 9) {
num3 = (num2-num1);
}
// We can't use num3 here because the compiler can't be sure that one of the assignments happened.