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

时间:2015-02-18 04:03:08

标签: c++ while-loop

这是一个非常具体的问题,但我的程序似乎在条件为假之前退出其while循环。我在调试时添加了相当多的内存检查以确保安全,它打印到屏幕,计数器为4,SqRoot最后为6,这意味着它应该仍然循环(TestNum = 32)。我绝对知道它通过计数器< = SqRoot越过循环,因为它打印了两个"整数32是复合的"和"整数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 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);
}

2 个答案:

答案 0 :(得分:0)

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

顺便说一句,我添加了一行

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. 因此,只有当while的计算结果为false时,才会突破counter<=SqRoot循环。因此,在下面的代码中,

    if (counter<=SqRoot)
    {
       cout << "The integer " << TestNum << " is prime.\n";
    }
    
  3. 你永远不会在if区块中执行该行。

    如果在检测到复合时断开while循环并将最后if块中的逻辑更改为:

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

答案 1 :(得分:-2)

为什么如此奇怪地检查素数?

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