是否可以更简洁地编写以下代码?
if ((count % 100 == 1) || (count % 100 == 21) || (count % 100 == 31)) return "рубль";
else if ((count % 100 == 41) || (count % 100 == 51) || (count % 100 == 61)) return "рубль";
else if ((count % 100 == 71) || (count % 100 == 81) || (count % 100 == 91)) return "рубль";
答案 0 :(得分:2)
您要查找以十进制表示形式以1
(count % 10 == 1
)结尾的数字,除了那些以十进制表示形式以11(count % 100 != 11
)结尾的数字,所以
if (count % 10 == 1 && count % 100 != 11)
return "рубль";
以不同的方式输入
if ((count % 100 == 1) || (count % 100 == 21) || (count % 100 == 31)) return "рубль";
else if ((count % 100 == 41) || (count % 100 == 51) || (count % 100 == 61)) return "рубль";
else if ((count % 100 == 71) || (count % 100 == 81) || (count % 100 == 91)) return "рубль";
等效于
if (
count % 100 == 1 ||
// count % 100 == 11 || // Intentionally omitted.
count % 100 == 21 ||
count % 100 == 31 ||
count % 100 == 41 ||
count % 100 == 51 ||
count % 100 == 61 ||
count % 100 == 71 ||
count % 100 == 81 ||
count % 100 == 91
) {
return "рубль";
}
这已经更具可读性,但是我们可以做得更好。
如果我们可以添加count % 100 == 11
,则条件将更加统一,这可能会为简化提供途径。因此,让我们尝试一下。
if (count % 100 != 11) {
if (
count % 100 == 1 ||
count % 100 == 11 ||
count % 100 == 21 ||
count % 100 == 31 ||
count % 100 == 41 ||
count % 100 == 51 ||
count % 100 == 61 ||
count % 100 == 71 ||
count % 100 == 81 ||
count % 100 == 91
) {
return "рубль";
}
}
实际上,我们现在可以将大条件简化如下:
if (count % 100 != 11) {
if (count % 10 == 1) {
return "рубль";
}
}
最后,您可以通过对嵌套if
的条件进行“与”操作来折叠它们。
if (count % 100 != 11 && count % 10 == 1)
return "рубль";
更具可读性:
if (count % 10 == 1 && count % 100 != 11)
return "рубль";
答案 1 :(得分:0)
for (int i = 1; i <= 91; i += 10)
if (count % 100 == i)
return "Please use english / Пожалуйста учи английский";