简体   繁体   English

如何简化这个条件?

[英]How to simplify this condition?

I'm learning about using if-else else-if conditions and I am wondering if there is anyway to simplify these statement below.我正在学习如何使用if-else else-if条件,我想知道是否有任何方法可以简化下面的这些语句。 Can I combine all of them into one statement?我可以将所有这些组合成一个声明吗?

if (a < 0) {
    a = 1;
}
if (b < 0) {
    b = 1;
}
if (c < 0) {
    c = 1;
}

It seems not possible to combine all your mentioned if statements into one as a , b , c are all independent variables.似乎不可能将您提到的所有 if 语句合并为一个,因为abc都是自变量。 However, to make your code more readable, you can take advantage of method.但是,为了使您的代码更具可读性,您可以利用方法。

eg Implement a method like this:例如实现这样的方法:

int processNegativeNumber(int num) {
    if (num < 0) {
        return 1;
    }
    return num;
}

Now, you can call it like this:现在,你可以这样称呼它:

a = processNegativeNumber(a);
b = processNegativeNumber(b);
c = processNegativeNumber(c);

You could use ternary operator to save some chars:-)您可以使用三元运算符来保存一些字符:-)

a = a < 0 ? 1 : a;
b = b < 0 ? 1 : b;
c = c < 0 ? 1 : c;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM