此代码显示错误"stu undeclared" ??我该怎么办

This code shows error "stu undeclared"?? what should i do

本文关键字:代码 我该怎么办 undeclared stu 错误 显示      更新时间:2023-10-16

我知道这个错误是因为我在for循环范围内声明了stu,但这是程序的必要性。我想为每个测试用例声明一个数组(测试用例应该一次全部输入)。请告诉我实现这一目标的方法。动态内存是另一种选择吗?

#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
    int t;
    cin>>t;
    int n[t],g[t];
    int m =0;
    for(int w=0;w<t;t++)
    {
        cin>>n[w]>>g[w];
        int stu[n[w]];
        for(int i=0;i<n[w];i++)
        {
            cin>>stu[i];
        }
    }    
    while(m<t)
    {
        int a,b;    
        int e;
        e = (n[m]*(n[m]-1))/2;
        int diff[e];
        if (g[m]=1)
        {
            cout<<0<<endl;
            return 0;
        }
        b=*(min_element(stu,stu+n[m]-1));
        a=*(max_element(stu,stu+n[m]-1));
        if (g[m]=n[m])
        {
            cout<<a-b<<endl;
            return 0;
        }
        int z = 0;
        for(int j=0;j<(n[m]-1);j++)
        {
            for(int k=(j+1);k<n[m];k++)
            {
                diff[z]=abs(stu[j]-stu[k]);
                ++z;
            }
        }        
        cout<<*(min_element(diff,diff+e-1))<<endl;
        ++m;
    }    
    cin.ignore();
    cin.get();
    return 0;
} 

您在for循环中声明stu,因此它被限制在循环的范围内。然后尝试在循环之外使用它,在那里它是未声明的。

for(int w=0;w<t;t++)
{
  ...
  int stu[n[w]]; // Beware: stu is a VLA. Non-standard C++.
  // OK to use stu here
  ...
}    
// stu doesn't exist here

还请注意,标准c++不支持可变长度数组(VLAs),这是您在stu声明中尝试使用的,以及这里:

int t;
cin>>t;
int n[t],g[t];

您可以将这些数组替换为std::vector<int>:

#include <iostream>
#include <vector>
int main()
{
  int t=0;
  cin>>t;
  std::vector<int> n(t);
  std::vector<int> g(t);
  std::vector<int> stu ...;
}

int stu[n[w]];

位于块内,在块外则不可见。你应该把它移出块,但这样做当然不能使用n[w],因为它是循环变量,你可以限制n[w]的最大值,例如

#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAXV = 100;
int main()
{
  int t;
  cin>>t;
  int n[t],g[t]; // <- supported by some compiler, but not std
  int m =0;
  int stu[MAXV];
  for(int w=0;w<t;t++) {
      cin>>n[w]>>g[w];
      for(int i=0;i<n[w] && i < MAXV;i++) {
        cin>>stu[i];
      }
  }    
  while(m<t) {
      int a,b;    
      int e;
      e = (n[m]*(n[m]-1))/2;
      int diff[e];
      if (g[m]==1) {
        cout<<0<<endl;
        return 0;
      } 
      b=*(min_element(stu,stu+n[m]-1));
      a=*(max_element(stu,stu+n[m]-1));
      if (g[m]==n[m]) {
        cout<<a-b<<endl;
        return 0;
      }
      int z = 0;
      for(int j=0;j<(n[m]-1);j++) {
        for(int k=(j+1);k<n[m];k++) {
          diff[z]=abs(stu[j]-stu[k]);
          ++z;
        }
      }        
      cout<<*(min_element(diff,diff+e-1))<<endl;
      ++m;
  }    
  cin.ignore();
  cin.get();
  return 0;
}        

(当我想你的意思是==而不是=时,我已经固定了一些条件赋值,但我还没有测试代码是否符合您的期望:它只是编译,与g++但不与其他编译器可能,请参阅代码中的注释)