此代码显示错误"stu undeclared" ??我该怎么办
This code shows error "stu undeclared"?? what should i do
我知道这个错误是因为我在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++但不与其他编译器可能,请参阅代码中的注释)
相关文章:
- 我的 cout 上有一个奇怪的输出,它把答案放在第一位,然后在我调用它的地方放一个奇怪的输出.我该怎么办?
- 当两个相等的双精度的相对比较不起作用时,我该怎么办?
- 我需要通过窗口句柄(HWND)获取文件,我该怎么办?
- 我正在"void value not ignored as it ought to be"我该怎么办?
- 未定义的引用错误,我该怎么办?
- 我在此代码中要求一个数字,如果用户给出一个字母,我该怎么办?
- 当一个功能完成另一个功能打开时,我该怎么办?
- 如果我尝试将 graphics.h 用于 c/c++ 时显示错误,我该怎么办?
- 这对我来说真的很难,我该怎么办
- 在C 中,我该怎么办才能格式化输出
- 当MPI中未知的发送消息数量时,我该怎么办
- 如果违反了利斯科夫替代原则,我该怎么办?
- 当(CUDA 7.5的)nvcc / cudafe++崩溃并出现段错误时,我该怎么办?
- 当来自外部库的线程不可预测地崩溃我的应用程序时,我该怎么办
- OpenGL红皮书示例中的无效代码.我该如何解决
- C++ 中的整数范围 - 当标准尚不存在时我该怎么办
- Visual Studio C++:获取未解析的令牌和未解析的链接.我该怎么办
- qextserialport在Windows上丢弃数据——我该怎么办
- 此代码显示错误"stu undeclared" ??我该怎么办
- 崇高文本在 CIN 之后不会继续我的代码。我该怎么办?