C++ “这是什么意思?”;错误:未在此范围内声明?“; #包括 #包括 使用名称空间std; int main() { 做 { 字符串名称、答案; cout
您在C++ “这是什么意思?”;错误:未在此范围内声明?“; #包括 #包括 使用名称空间std; int main() { 做 { 字符串名称、答案; cout,c++,C++,您在do块内声明了answer。但随后尝试在该范围块外引用answer 在main的顶部声明answer,而不是在do块中声明。您需要将answer的声明移到循环之外: #include <iostream> #include <string> using namespace std; int main () { do { string name, answer; cout << "Welcome to the prime
do
块内声明了answer
。但随后尝试在该范围块外引用answer
在
main
的顶部声明answer
,而不是在do
块中声明。您需要将answer
的声明移到循环之外:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
do
{
string name, answer;
cout << "Welcome to the prime number checker! Please enter your name: ";
getline (cin, name);
int a;
cout << "\nHello " << name;
cout << "\nPlease enter an integer: ";
cin >> a;
cin.sync();
if (a == 2)
{
cout << "\nThis is a prime number" << endl;
}
else
{
for (int b = 2; b < a; b++)
{
if (a % b == 0)
{
cout << "This number is not prime number" << endl;
break;
}
else
{
cout << "This number is a prime number." << endl;
break;
}
}
}
cout << "Do you want to do this again (Yes or No)?";
getline (cin, answer);
}
while (answer == "yes" || answer == "YES" || answer == "Yes"); //Not declared in this scope
return 0;
}
如果在循环内声明它,则在计算while
子句时,它就不再存在了。正如其他人所说,“answer”变量只存在于循环内-无法从循环外访问它
另一个建议是:不要检查所有可能的大小写排列,只需将整个字符串转换为小写。(实际上,您遗漏了几个-总共有6个,因为每个位置可能有2个可能的值中的一个。例如,可能类似“是”的内容仍应被接受为“是”)。也可能有一个(谨慎地)倾向于注意这种缩进会变得更加明显……另外,您可以通过只检查
2
和奇数来提高素数检测算法的性能。;(将for
循环的内部更改为从3
计数到sqrt(a)
,每次递增b
两次。答案对while条件隐藏,因此将其置于循环的上方
string answer;
do {
string name;
...
} while (answer == "yes" || answer == "YES" || answer == "Yes");