对于语句递增/递减错误

For statment increment/decrement error

本文关键字:错误 于语句 语句      更新时间:2023-10-16

我是使用C++的新手。我读过书,一直在使用互联网。在这里 - 练习 16 - https://en.wikibooks.org/wiki/C%2B%2B_Programming/Exercises/Iterations#EXERCISE_16(

我不明白为什么我的"for"陈述不起作用,当它似乎符合标准时。完整的代码如下,我将指出对我不起作用的位:

#include <iostream>
using namespace std;
void primecheck(int z)
{
    bool primes = true;
    // start at 1 because anything divisible by zero is an error
    for (int i=1; i<=z; i++)
    {
        if (z%i == 0)
        {
            // ignore if divisible by 1 or itself do nothing
            if ( i == z || i == 1)
            {}
            // if it can be divided by anything else it is not a prime
            else
            {
                primes = false;
                //break;
            }
        }
    }
    (primes == true) ? (cout << z << " is a prime number" << endl) : (cout << z << endl);
}
int main()
{
    int x;
    cout << "Enter a number to see if it is a prime number" << endl;
    cin >> x;
    for (x; x>0; x--)
    {
        primecheck(x);
    }
}

工作代码如上,但最初我有:

for (x; x<=1; x--)
{
    primecheck(x);
}

对我来说,这更有意义,因为我输入了一个高值,例如 5,并且我希望它减少到每个循环直到它为 1。但是每当我这样做时,它只是跳过了整个陈述。为什么会这样?

你需要这个:

for (; x>=1; x--)
{
    primecheck(x);
}

你之前说过的继续这个 for 循环,只要 x 是 <= 1。但是您的初始输入将大于 1(假设,因为您正在检查素数(,因此循环永远不会运行。换句话说,如果你输入任何大于1的数字(比如10(,它将检查条件10<=1。这将计算为 false,循环将终止

for (x; x<=1; x--)
{
    primecheck(x);
}

等效于以下while循环:

x;
while (x<=1)
{
    primecheck(x);
    x--;
}

那是:

  1. x;毫无意义,因为它什么都不做。
  2. for循环中间部分的条件不是停止条件。只要为真,循环就会运行。当您输入一个高值(如 5 (时,x<=1从一开始就为 false,因此循环永远不会运行。条件必须为 true 才能运行。