#include <iostream>
#include <iomanip>
using namespace std;
int col=10;
int row=0;
void avg(int * ar,int row, int col)
{
float size= row * col;
int sum=0, ave;
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++){
sum+=ar[i][j];
cout<<sum;}
}
ave=sum/size;
cout<<sum<<endl;
cout<<ave;
}
int main()
{
int row, col;
cout<<"How many rows does the 2D array have: ";
cin>>row;
cout<<"How many columns does the 2D array have: ";
cin>>col;
int ar[row][col];
cout<<"Enter the 2D array elements below : \n";
for(int i=0; i<row; i++){
cout<<"For row "<<i + 1<<" : \n";
for(int j=0; j<col; j++)
cin>>ar[i][j];
}
cout<<"\n Array is: \n";
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
cout<<setw(6)<<ar[i][j];
cout<<endl;
}
cout<<"\nAverage of all the elements of the given D array is: \n";
avg((int*)ar,row,col);
return 0;
}嗨,我写了这个代码来计算二维数组元素的平均值。我在试图访问第12 -13 ari行中的2D数组元素时出错。
错误是-错误:数组下标的无效类型‘intint’
如何解决这个错误?
PS:我想划船(不)。2维数组中的行)和col(no.)函数参数中的列),以使其更具动态性。
发布于 2022-01-18 04:48:16
函数参数ar是int*。但是,当您编写sum+=ar[i][j]时,您订阅它就好像我们有一个2D数组一样。您只能为一维(如arr[i] )下标。
和、row和col是而不是常量表达式。在标准C++中,数组的大小必须是编译时间常数(常量表达式)。所以,
int ar[row][col]; //this statement is not standard c++上面的语句是而不是标准的c++。
一个更好的方法(避免这些问题)是使用2D std::vector而不是2D数组,如下所示。
#include <iostream>
#include <iomanip>
#include <vector>
//this function takes a 2D vector by reference and returns a double value
double avg(const std::vector<std::vector<int>> &arr)
{
int sum=0;
for(const std::vector<int> &tempRow: arr)
{
for(const int &tempCol: tempRow){
sum+=tempCol;
//std::cout<<sum;
}
}
return (static_cast<double>(sum)/(arr.at(0).size() * arr.size()));
}
int main()
{
int row, col;
std::cout<<"How many rows does the 2D array have: ";
std::cin>>row;
std::cout<<"How many columns does the 2D array have: ";
std::cin>>col;
//create a 2D vector instead of array
std::vector<std::vector<int>> ar(row, std::vector<int>(col));
std::cout<<"Enter the 2D array elements below : \n";
for(auto &tempRow: ar){
for(auto &tempCol: tempRow){
std::cin>>tempCol;
}
}
std::cout<<"\n Array is: \n";
for(auto &tempRow: ar)
{
for(auto &tempCol: tempRow)
std::cout<<std::setw(6)<<tempCol;
std::cout<<std::endl;
}
std::cout<<"\nAverage of all the elements of the given D array is: \n";
std::cout<<avg(ar);
return 0;
}以上程序的输出可以看到这里。
发布于 2022-01-18 04:44:15
您遇到问题的原因是您试图动态分配一个2D数组(而不是静态的)。
静态分配是指在代码运行之前,指定行和列的值。示例:int ar[35][35],这将在编译时创建一个35x352D数组。
动态分配意味着在运行时(编译后,运行时)更改行和列的值。这将需要使用C++中的C++语句在函数avg的开头创建一个指定大小的新数组。在C++中有很多关于数组动态分配的信息,比如本文中的这里
https://stackoverflow.com/questions/70750236
复制相似问题