代码分析整数并询问用户是否要在结尾处分析另一个整数。我把它设置在while循环中,只有在'again'为真时运行。最后,用户输入“n”表示“否”,不运行其他数字。问题是程序再次运行,即使再次= false。
如何修复循环? 我认为主要关注的是我的开关所在的底部,但我发布了所有内容以防万一我在代码的主要部分看了一些。
int main()
{
bool again = true;
bool flag = false;
int usernum;
int count = 0;
int userhold1, userhold2;
userhold1 = 0;
userhold2 = 0;
char choice;
while ( again = true )
{
cout << "Please enter a positive integer: "; // Getting the number to test
cin >> usernum;
cout << endl;
////////////////////////////////// Finding the Factors
cout << "The factors of " << usernum << " are: ";
for (int i=1 ; i <= usernum/2 ; i++)
{
if( isAfactor ( usernum , i , flag) )
{
cout << i << ", ";
count = count + i; // Keeping track of sum of factors
}
}
cout << "and " << usernum << endl;
count = count + usernum;
////////////////////////////////// Sum of Factors
cout << "The sum of the factors is: " << count << endl;
////////////////////////////////// Prime Factorization
cout << "The prime factorization is: ";
getPrimeFac ( usernum );
cout << endl;
////////////////////////////////// Even/Odd Checker
cout << usernum << " is an ";
if ( checkeven( usernum ) == true)
cout << "EVEN number." << endl;
else
cout << "ODD number." << endl;
////////////////////////////////// Prime Checker
PrimeCheck (usernum);
////////////////////////////////// Perfect , Abundant , Deficient
count = 0;
for ( int i = 1 ; i <= usernum/2 ; i++ ) // Adding the factors of the number
{
if( isAfactor ( usernum , i , flag ) )
count = count + i; // Suming of factors
}
if ( count == usernum )
cout << usernum << " is a PERFECT number." << endl;
else if ( count > usernum )
cout << usernum << " is an ABUNDANT number." << endl;
else if ( count <usernum )
cout << usernum << " is a DEFICIENT number." << endl;
////////////////////////////////// Squares
SquareCheck ( usernum );
////////////////////////////////// Twin Primes
if ( PrimeCheck2 ( usernum ) == true )
{
if ( PrimeCheck2 ( usernum -2 ) == true )
{
userhold1 = ( usernum - 2 );
cout << usernum << " has a twin prime: " << userhold1 << " ";
if ( PrimeCheck2 ( usernum + 2 ) == true )
{
userhold2 = ( usernum + 2 );
cout << "and " << userhold2;
}
}
if ( PrimeCheck2 ( usernum + 2 ) == true )
{
userhold1 = ( usernum + 2 );
cout << usernum << " has a twin prime: " << userhold1 << " ";
if ( PrimeCheck2 ( usernum - 2 ) == true )
{
userhold2 = ( usernum - 2 );
cout << "and " << userhold2;
}
}
}
cout << endl << endl;
////////////////////////////////// End program again?
cout << "Would you like to analyze another number? (y/n) :";
cin >> choice;
switch (choice)
{
case 'y': again = true;
break;
case 'n': again = false;
break;
}
}
system ("pause");
}
答案 0 :(得分:1)
此行将再次设置为true,然后再次返回新值,因此它始终为真。
while ( again = true )
请改为尝试:
while ( again == true )
甚至更好:
while ( again )
答案 1 :(得分:1)
更改
while(again=true)
到
while(again == true)
或
while(again)
答案 2 :(得分:0)
使用=
是一个赋值语句。要进行比较,请使用==
while (again == true) {
//do code
}