在C++中IF语句的自变量字段中循环集成

在C++中IF语句的自变量字段中循环集成,c++,if-statement,C++,If Statement,我正在努力解决一道数学题。 我想做的是用一个if语句将变量n与一组变量I 1到10进行比较。在C++中有什么方法可以做到吗? 以下是我试图做的: int smallPos(int n){ if (n%for(int i=1;i<=10;i++)==0) { return n; } 这显然是错误的,但有什么办法可以避免吗?您要做的是: int smallPos(int n) { for (int i = 1; i <= 10; ++i)

我正在努力解决一道数学题。 我想做的是用一个if语句将变量n与一组变量I 1到10进行比较。在C++中有什么方法可以做到吗? 以下是我试图做的:

 int smallPos(int n){
     if (n%for(int i=1;i<=10;i++)==0) {
        return n;
      }

这显然是错误的,但有什么办法可以避免吗?

您要做的是:

int smallPos(int n)
{
    for (int i = 1; i <= 10; ++i)
    {
        if (n % i != 0) // check if n % i == 0, if not, then we shouldn't return n.
        { 
            return -1; // or whatever you want to return when not ALL the remainders are 0.
        }
    }

    return n; // If we get here then all the remainders were 0s.
}

您要做的是:

int smallPos(int n)
{
    for (int i = 1; i <= 10; ++i)
    {
        if (n % i != 0) // check if n % i == 0, if not, then we shouldn't return n.
        { 
            return -1; // or whatever you want to return when not ALL the remainders are 0.
        }
    }

    return n; // If we get here then all the remainders were 0s.
}

看起来您正在尝试这样做:

int smallPos(int n)
{
    return (n % 232792560 == 0) ? n : <sentinel value>; // sentinel_value is the value return if n does not meet requirements
    //232792560 is the first number for which n % a: a ∈ {1,2,3...10} This is faster than checking each of these values.
}

看起来您正在尝试这样做:

int smallPos(int n)
{
    return (n % 232792560 == 0) ? n : <sentinel value>; // sentinel_value is the value return if n does not meet requirements
    //232792560 is the first number for which n % a: a ∈ {1,2,3...10} This is faster than checking each of these values.
}

如果所有的值1-10都是零余数,我只能返回n。也就是说,如果其中至少有一个不产生零余数,那么n就不应该返回!我明白了,这很聪明。谢谢大家!+1是一个清晰的答案,但请参阅我的答案以获得优化版本。如果所有值1-10都导致零余数,则我只能返回n。也就是说,如果其中至少有一个不产生零余数,那么n就不应该返回!我明白了,这很聪明。谢谢大家!+1以获得清晰的答案,但请参阅我的答案以获得优化版本。