我有一项任务,我需要计算成绩。下面的代码块将用户输入“sections”并将其乘以4,同时将总输出限制为20.根据赋值,我们不能使用if / else语句,但这是我能想到的所有限制输出到20.也许使用简单的数学方法?但我想不出一个简单的方法来做到这一点。
public static int calcDGrade(int sections) //method to calculate the grade for the students sections
{
int maxDGrade = ((sections*4));
if (maxDGrade > 20) //limits total score to 20
{
return 20;
}
else
{
return maxDGrade;
}
}
答案 0 :(得分:2)
您可以使用ternary operator:
return maxDGrade > 20 ? 20 : maxDGrade;
三元操作包括以下部分:
condition ? A : B
其中A是条件评估为true
时的操作结果,如果条件评估为B
,则结果为false
。
对于您的示例,如果20
大于20,它将返回maxDGrade
,否则它将返回maxDGrade
的值。换句话说,它相当于说:
if (maxDGrade > 20) {
return 20;
} else {
return maxDGrade;
}
答案 1 :(得分:2)
您可以使用Math.min(int, int)
获取最低20分和其他值。像
int maxDGrade = Math.min(20, sections*4);
因为您需要20
或乘法的结果,更低。