迭代计数器不递增

Vla*_*adp 3 c++

我用c ++编写了一个程序来打印所有素数高达100,但它只是写入"hello world",然后挂起.这是为什么?

#include <iostream>

bool is_prime(int num)
{
    if(num == 1)
    {
        return false;
    }
    for(int i = 2; i < num; i++)
    {
        if(num % i == 0)
        {
            return false;
        }
    }
    return true;
}

int increase(int i)
{
    return i++;
}

int main()
{
    std::cout << "hello world!!" << std::endl;
    int i = 1;
    while(i < 100)
    {
        i = increase(i);
        if(is_prime(i))
        {
            std::cout << i << " is prime" << std::endl;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Hab*_*bib 22

return i++;此语句将返回原始值i,而不是递增值.

你需要return ++i;return i + 1 (感谢@interjay指出).后者return i + 1;明确指出只有返回值很重要,而不是新值i.

后增量的效果i++将在下一行(或使用i)中可见.

不确定,如果你需要一个单独的方法来递增你的变量i,你可以在你的while循环中做到这一点.

 while(i < 100)
    {

        if(is_prime(i))
        {
            std::cout << i << " is prime" << std::endl;
        }
        i++;
    }
Run Code Online (Sandbox Code Playgroud)

您也可以使用for循环,而不是while因为您正在处理一系列值.

for(i = 1; i < 100; i++)
{
    if(is_prime(i))
    {
        std::cout << i << " is prime" << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 实际上,`return i + 1`比任何一个都好,因为它清楚地表明返回的值是唯一重要的,而不是`i`的新值. (11认同)

Rah*_*thi 10

试试这个:

int increase(int i)
{
    return ++i;
}
Run Code Online (Sandbox Code Playgroud)

要获得ielse 的递增值,您将获得i的原始值,这将导致您无限循环.

更好的方法是使用(为清晰起见):

int increase(int i)
{
    return i+1;
}
Run Code Online (Sandbox Code Playgroud)