在条件为false之前循环时退出
Exits while loop before condition is false?
这是一个非常具体的问题,但我的程序似乎在条件为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
原因:
当您检测到一个数字是一个复合数时,您不会突破
while
循环。因此,只有当
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;
}
}
相关文章:
- 退出简单while循环时出现问题
- 虽然循环在使用回车键时不退出程序
- C++ 自动点击器未退出循环
- 使用 while 或 do while 退出循环
- 虽然循环即使应用了错误条件也不会退出
- 如何使用布尔值(C++)退出while循环
- 如果我按enter键,我如何退出c++中的循环
- Craps游戏在循环不满足退出条件时执行
- 如何修复不会在退出选择时终止的 do-while 循环
- 为什么循环退出不会?
- 如何退出 for 循环内的嵌套 if-else 语句?(C/C++)
- 代码不会退出 while 循环
- 为什么当我进入退出条件时,程序会打印两倍的默认条件而不是退出 while 循环?
- 退出选项和 while 循环C++
- 为什么在接受输入后循环退出时不会这样做
- 试图调节我的 do-while 以停止在终端中退出程序.菜单不会根据需要循环使用当前语句
- 如何在 "if" 和 "while" 语句中只允许 3 个值以允许循环退出
- 为什么在循环退出时不这样做?
- while循环退出后,将删除字符串的内容
- For循环退出条件(size_t vs. int)