#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 ar[i][j] 的二維陣列的陣列元素時出現錯誤
錯誤說-錯誤:陣列下標的無效型別'int [int]'
我該如何解決這個錯誤?
PS:我想在函式引數中給出行(二維陣列中的行數)和列(二維陣列中的列數)以使其更具動態性。
uj5u.com熱心網友回復:
您的函式引數ar是 a int*。但是當你寫的時候,你給sum =ar[i][j]它下標,就好像我們有一個二維陣列一樣。您只能為它下標一維,例如arr[i].
此外,row和col不是常量運算式。在標準 C 中,陣列的大小必須是編譯時常量(常量運算式)。所以,
int ar[row][col]; //this statement is not standard c
上面的陳述句不是標準的 c 。
更好的方法(避免這些問題)是使用 2Dstd::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;
}
上述程式的輸出可以在這里看到。
uj5u.com熱心網友回復:
您遇到問題的原因是因為您正在嘗試動態分配 2D 陣列(而不是statically)。
靜態分配意味著在代碼運行之前,[row] 和 [column] 的值被指定。示例:int ar[35][35]
這將在編譯時創建一個 35x35 二維陣列。
動態分配意味著在運行期間(編譯后,運行時)更改 [row] 和 [column] 的值。這將需要使用newC 中的陳述句在函式的開頭創建一個指定大小的新陣列avg。有很多關于 C 中陣列動態分配的資訊,比如這里的這篇文章
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414921.html
標籤:
