Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ “这是什么意思?”;错误:未在此范围内声明?“; #包括 #包括 使用名称空间std; int main() { 做 { 字符串名称、答案; cout_C++ - Fatal编程技术网

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");