English 中文(简体)
C++if语句似乎忽略了参数
原标题:C++ if statement seems to ignore the argument

这是代码。

bool b_div(int n_dividend)
{
    for (int iii = 10 ; iii>0 ; iii--)
    {
        int n_remainder = n_dividend%iii;
        if (n_remainder != 0)
         return false;
        if (iii = 1)
         return true;

    }
}

在测试了我为程序制作的这个函数后,这个函数似乎在if(n_remains!=0)部分停止了。现在,函数应该测试函数接收的数字是否可以除以从10到1的所有数字。所以我希望得到一些建议!我很难排除故障!我应该寻找的任何链接或单词都会很棒!我对编程还很陌生,所以你能为学习提供的任何帮助都会让我大吃一惊!谢谢

最佳回答

将上一次if语句更改为:

if (iii == 1)
  return true;

目前,您只有一个等号,它将变量iii设置为1,并且始终为true。通过使用双等于,它将比较iii和1。

问题回答

除了SC Ghost的答案,你实际上还可以进一步清理你的功能:)

bool b_div(int n_dividend) {
    for (int i = 10 ; i > 1 ; i--) {
        int n_remainder = n_dividend % i;
        if (n_remainder != 0) {
            return false;
        }
    }
    return true;
}

需要注意的是,

  1. modulus of 1 will always be zero, so you only need to iterate while i > 1
  2. you can completely remove the if(i == 1) check and just always return true after the for loop if the for loop doesn t return false. It basically removes an unnecessary check.
  3. I think it s more standard to name your iterator iii as i, And I prefer brackets the way I wrote them above (this is of course completely personal preference, do as you please)




相关问题
Detect months with 31 days

Is there an analogous form of the following code: if(month == 4,6,9,11) { do something; } Or must it be: if(month == 4 || month == 6 etc...) { do something; } I am trying to write an if ...

&& (AND) and || (OR) in IF statements

I have the following code: if(!partialHits.get(req_nr).containsKey(z) || partialHits.get(req_nr).get(z) < tmpmap.get(z)){ partialHits.get(z).put(z, tmpmap.get(z)); } where partialHits ...

If / else order sequence issue

I have the following set up, a ddl (ddlProd, radBuyer) and autocomplete text box (txtProdAC, radProd) that when populated and their respective radio buttons are selected, a grid view of the data is ...

PHP if or statement not working

We are trying to use the below piece of code if (($_GET[ 1 ] != "1") || ($_GET[ 1 ] != "2")) { When we try this no matter what value the variable has it will evaluate as true even when data is ...

C++ String manipulation - if stament

I have the following code that works correctly. However after I add an else statement anything always evaluates to else wgetstr(inputWin, ch); //get line and store in ch variable str = ch; ...

Are one-line if / for -statements good Python style?

Every so often on here I see someone s code and what looks to be a one-liner , that being a one line statement that performs in the standard way a traditional if statement or for loop works. I ...

Which is faster - if..else or Select..case?

I have three condition to compare. Which one is more faster between the following two? Please point me out. Thanks all! If var = 1 then Command for updating database ElseIf var = 2 then ...

热门标签