在条件为false之前循环时退出

Exits while loop before condition is false?

本文关键字:循环 退出 条件 false      更新时间:2023-10-16

这是一个非常具体的问题,但我的程序似乎在条件为false之前退出了while循环。当我调试时,为了安全起见,我添加了很多内存检查,它在屏幕上显示计数器为4,SqRoot最后为6,这意味着它应该仍然在循环(TestNum=32)。我肯定知道它正在通过计数器<SqRoot,因为它同时打印"整数32是复合的"answers"整数32为素数"。非常感谢您的帮助!非常感谢

编辑:我改变了程序的整体逻辑,现在它正在运行。谢谢

#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 byn";
        };
        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);
}

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

顺便说一句,我添加了行

cout << endl;

线后

cout << " DivFloat " << DivFloat;

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

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

整数32是复合的。32可被整除4 8counter*4 TestNum 32 DivInt 8 SqRoot 6 DivFloat 8计数器7 TestNum 32 DivInt 4 SqRoot 6 DivFloat 4.57143

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

计数器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块中的行。

当您检测到一个复合并将最后一个if块中的逻辑更改为:时,如果您突破了while循环,则程序应该表现正确

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

为什么对素数进行如此奇怪的检查?

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