C++ - "My_Array"未在此范围内声明 - 简易程序

C++ - "My_Array" is not declared in this scope - Easy Program

本文关键字:范围内 简易程序 声明 Array My C++      更新时间:2023-10-16

所以我正在编写一个非常基本的代码,它应该遍历一个数组(尽管我实现这个的效率很低),并查看数组中的任何两个元素是否等于第三个预定义的和。然而,我一直得到一个"未在此范围内声明"的问题,我不知道为什么,因为这都在同一个函数中。

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
int n=0, sum = 0, key = 1, counter = 0; 
cout << "Please enter the number of variables you wish to compare:" <<" ";
cin >> n ;
if (n < 2)
{
    do
        {
            cout<<"Error! -- you must enter 2 or more variables to     continue!"<< endl<< "Please enter the number of variables you wish to compare:" <<" ";
            cin >> n;
        } while (n <2);
}
else
{
    int My_Array[n];
    cout << "Please Enter "<< n <<" numbers" <<endl;
    for (int i=0; i<n; i++)
    {
        cin >> My_Array[i];
        cout << "You've entered"<<" "<<i+1<<" numbers"<<endl<<endl;
    }
}
cout << "Please enter the number to which you believe the addens are present in the previously entered number(s):"<<" ";
cin >> sum;
for (int i=0; i<n; i++)
    {
      key = sum - My_Array[i];
      for (int j = 0; j<n; j++)
        {
            if(key - My_Array[j] == 0)
                {
                    counter++;
                 }
        }
    }
cout <<"There are "<< counter << " numbers that equal "<< sum<<" in this array";
}

您在else块中声明了My_Array。一旦控制从该块中传递出去,就堆栈而言,它不再存在,您可以不引用它。