我正在尝试编写一个程序,该程序将具有数组的用户输入大小,然后将值取入该数组。我最初尝试过
int sz = 51;
double Arr[sz];
导致编译错误。显然变量的动态分配必须发生,如果可能的话我宁愿避免这种情况。所以我修改了我的代码(如下所示的当前状态),它现在只抛出“']' 标记之前的预期主表达式”。有没有办法解决这个问题,但我只是没有看到它,还是我需要使用动态分配?
感谢您的宝贵时间!
#include <iostream>
#include <iomanip> //for setprecision
using namespace std;
int sz = 51;
double n=0;
double Arr[0];
void get_input(double Arr[], int &sz){ //gets input
do{
cout<< "Enter size: "<< endl;
cin>> sz;
if (sz<0 || sz>50){
cout<< "Invalid size, enter a value between 0 and 50"<<endl;
}
}while(sz<0 || sz>50);
for( int i=0; i<sz; i++){
cin>> Arr[i];
}
}
double calcSum( double Arr[], int sz){ //finds sum
for(int i=0; i<sz; i++){
n+= Arr[i];
}
return(n);
}
void printArray(double Arr[], int sz){ //prints array elements
for(int i=0; i<sz; i++){
cout<< Arr[i]<< setprecision(2)<<" ";
if(i%7 == 0)
cout<< endl;
}
}
int main()
{
double Arr[sz];
get_input(Arr[], sz); //error here
printArray(Arr[], sz); //error here
return 0;
}
最佳答案
VLAs (例如 Arr[sz]
)仅在 C++ 中作为扩展被支持。它们不是官方语言标准的一部分。您应该改用 std::vector
。
关于用户输入的 C++ 数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33620143/