【发布时间】:2015-02-18 12:57:12
【问题描述】:
这是一个非常具体的问题,但我的程序似乎在条件为假之前退出了它的 while 循环。我在调试时添加了很多内存检查以确保安全,它在屏幕上显示计数器为 4,最后 SqRoot 为 6,这意味着它仍应循环通过 (TestNum=32)。我绝对知道它通过 counter
编辑:我改变了程序的整体逻辑,它现在可以工作了。谢谢!
#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);
}
【问题讨论】:
-
它在 if 中打印变量。它只是不再进入它,但循环继续。
-
我最初是这么认为的,但我在 if 中将星号添加到“计数器”中,这是正在打印的最终检查。此外,它同时打印“整数 32 是复合数”和“整数 32 是素数”,因此它通过 counter 循环
-
在我的最后工作完全正常(对于那个特定的测试用例)!你得到的确切错误是什么?我唯一看到的是您缺少
}的main() -
@binaryBaBa 问题在于它同时打印“整数 32 是复合数”和“整数 32 是素数”。
if (counter<=SqRoot)是对添加的循环的检查。一旦它退出 while 循环,counter -
您的系统可能出现舍入错误。如果您要使用
++作为循环计数器,那么变量应该是一个整数,而不是float。我建议将counter更改为int,并将SqRoot更改为double SqRoot = sqrt(TestNum)+0.5;- 这样您就可以避免任何接近整数的舍入问题。
标签: c++ while-loop