1

如何检查一个条件是否传递了多个值?

例子:

if(number == 1,2,3)

我知道逗号不起作用。

4

9 回答 9

3
if (number == 1 || number == 2 || number == 3)
于 2009-10-07T14:38:47.790 回答
3

如果您使用的是 PHP,那么假设您的数字列表是一个数组

$list = array(1,3,5,7,9);

然后对于任何元素,您可以使用

if(in_array($element, $list)){
//Element present in list
}else{
//not present.
}

功能结构:

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

希望有帮助。

于 2011-06-13T17:46:11.137 回答
1
if ((number >= 1) && (number <= 3))
于 2009-10-07T14:37:55.870 回答
1

什么语言?

例如,在 VB.NET 中使用 OR,而在 C# 中使用 ||

于 2009-10-07T14:38:30.223 回答
1

由于您未指定语言,因此我添加了 Python 解决方案:

if number in [1, 2, 3]:
    pass
于 2009-10-07T14:41:11.420 回答
0

在 T-SQL 中,您可以使用 IN 运算符:

select * from MyTable where ID in (1,2,3)

如果您使用的是集合,则可能有一个包含运算符,用于另一种方式来执行此操作。

在 C# 中,另一种可能更容易添加值的方式:

    List<int> numbers = new List<int>(){1,2,3};
    if (numbers.Contains(number))
于 2009-10-07T14:40:33.950 回答
0

我将假设一个 C 风格的语言,这里是 IF AND OR 逻辑的快速入门:

if(variable == value){
    //does something if variable is equal to value
}

if(!variable == value){
    //does something if variable is NOT equal to value
}

if(variable1 == value1 && variable2 == value2){
    //does something if variable1 is equal to value1 AND variable2 is equal to value2
}

if(variable1 == value1 || variable2 = value2){
    //does something if variable1 is equal to value1 OR  variable2 is equal to value2
}

if((variable1 == value1 && variable2 = value2) || variable3 == value3){
    //does something if:
    // variable1 is equal to value1 AND variable2 is equal to value2
    // OR variable3 equals value3 (regardless of variable1 and variable2 values)
}

if(!(variable1 == value1 && variable2 = value2) || variable3 == value3){
    //does something if:
    // variable1 is NOT equal to value1 AND variable2 is NOT equal to value2
    // OR variable3 equals value3 (regardless of variable1 and variable2 values)
}

因此,您可以看到如何将这些检查链接在一起以创建一些非常复杂的逻辑。

于 2009-10-07T14:46:26.417 回答
0

对于整数列表:

static bool Found(List<int> arr, int val)
    {
        int result = default(int);
        if (result == val)
            result++;

        result = arr.FindIndex(delegate(int myVal)
        {
            return (myVal == val);
        });
        return (result > -1);
    }
于 2009-10-07T14:52:15.953 回答
0

在 Java 中,您有包装原始变量的对象(整数表示 int,Long 表示 long 等)。如果您希望比较大量完整数字(整数)之间的值,您可以做的是启动一堆 Integer 对象,将它们填充到诸如 ArrayList 之类的可迭代对象中,遍历它们并进行比较。

就像是:

ArrayList<Integer> integers = new ArrayList<>();
integers.add(13);
integers.add(14);
integers.add(15);
integers.add(16);

int compareTo = 17;
boolean flag = false;
for (Integer in: integers) {
    if (compareTo==in) {
    // do stuff
    }
}

当然,对于一些值,这可能有点笨拙,但如果你想与很多值进行比较,它会很好地工作。

另一种选择是使用 java Sets,您可以放置​​许多不同的值(集合将对您的输入进行排序,这是一个加号),然后调用该.contains(Object)方法来定位相等性。

于 2015-08-04T08:55:16.487 回答