在条件为假之前退出 while 循环?

Exits while loop before condition is false?

这是一个非常具体的问题,但我的程序似乎在条件为假之前退出了它的 while 循环。我在调试时添加了很多内存检查以确保安全,它在屏幕上打印出计数器为 4,最后 SqRoot 为 6,这意味着它应该仍在循环 (TestNum=32)。我肯定知道它通过了 counter<=SqRoot 的循环,因为它同时打印 "The integer 32 is composite" 和 "The integer 32 is prime"。非常感谢任何帮助!非常感谢

编辑:我更改了程序的整体逻辑,现在可以正常工作了。谢谢!

#include <iostream>
#include <cmath>
using namespace std;

//Declare variables.
int TestNum, DivInt, SqRoot, PrintCounter(0), oppcounter;
float DivFloat, counter(2);

int main()
{
//Prompt user for input.
cout << "Input an positive integer to test its primality.";
cin >> TestNum;

//Check if input is positive.
while (TestNum < 0)
{
    cout << "Please input a *positive* integer.";
    cin >> TestNum;
}

//Square root.
SqRoot = sqrt(TestNum)+1;

//Loop to test if prime.
while (counter<=SqRoot)
{
    ++counter;
    DivFloat = TestNum/counter;
    DivInt = TestNum/counter;
    oppcounter = TestNum/counter;
    if (DivFloat-DivInt == 0)
    {
        ++PrintCounter;
        if (PrintCounter==1)
        {
        cout << "The integer " << TestNum << " is composite.\n " \
                << TestNum << " is divisible by\n";
        };

        cout << counter << "  " << oppcounter;

        cout << "counter* " << counter;
        cout << " TestNum " << TestNum;
        cout << " DivInt " << DivInt;
        cout << " SqRoot " << SqRoot;
        cout << " DivFloat " << DivFloat;
    }
}

if (counter<=SqRoot)
{
    cout << "The integer " << TestNum << " is prime.\n";
}

cout << "counter " << counter;
cout << " TestNum " << TestNum;
cout << " DivInt " << DivInt;
cout << " SqRoot " << SqRoot;
cout << " DivFloat " << DivFloat;

//End main.
return (0);
}

为什么质数检查这么奇怪?

for(int i = 2; i*i <= n; ++i)
{
     if (n % i == 0)
     {
          cout << "not prime";
          break;
      }
 }

我看到的行为与您所描述的相反,我知道为什么。您发布的代码可能与您正在执行的代码不同。

顺便说一句,我添加了行

cout << endl;

行后

cout << " DivFloat " << DivFloat;

在几个地方使输出更具可读性。

当我输入 32 时,我看到以下输出:

The integer 32 is composite.
 32 is divisible by
4  8
counter* 4 TestNum 32 DivInt 8 SqRoot 6 DivFloat 8
counter 7 TestNum 32 DivInt 4 SqRoot 6 DivFloat 4.57143

当我输入 17 时,我看到以下输出:

counter 6 TestNum 17 DivInt 2 SqRoot 5 DivFloat 2.83333

原因:

  1. 当您检测到一个数字是合数时,您不会跳出 while 循环。

  2. 因此,只有当 counter<=SqRoot 的计算结果为 false 时,您才会跳出 while 循环。结果,在下面的代码中,

    if (counter<=SqRoot)
    {
       cout << "The integer " << TestNum << " is prime.\n";
    }
    

你永远不会执行 if 块中的行。

如果您在检测到组合时跳出 while 循环并将最后一个 if 块中的逻辑更改为:

,程序应该会正常运行
if (counter > SqRoot)
{
   cout << "The integer " << TestNum << " is prime.\n";
}