我遇到了一个没有执行功能的程序的困难,我似乎无法找到问题。
我尝试编写的这段代码应该要求用户输入二维数组的大小,然后搜索每一行并计算行的平均值。
执行得很好,直到计算结果出现。
示例:
Enter the size of the array: 2
2
Enter the element of the 1 row and 1 column: 10
Enter the element of the 1 row and 2 column: 20
Enter the element of the 2 row and 1 column: 50
Enter the element of the 2 row and 2 column: 20
Program ended with exit code: 0
和程序代码:
#include <iostream>
#include <iomanip>
using namespace std;
void calculate(int n, int m, int matrix[10][10], double sum, double avg[10], int k); //to calculate the average of each row
void input(int n, int m, int matrix[10][10]); //to input the requirements
void results(double avg[10],int n); //to output the results
int main() {
int matrix[10][10]; //the array
int n,m; //rows and columns entered by the user
double avg[10]; //average of the array rows, which will be calculated later
int k; //number of positive elements
double sum; //to calculate sum
input(n, m, matrix);
calculate(n, m, matrix, sum, avg, k);
results(avg, n);
return 0;
}
void input(int n, int m, int matrix[10][10]) {
cout<<"Enter the size of the array: ";
cin>>n>>m; //the real elements of the array
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
cout<<"Enter the element of the "<<i+1<<" row and "<<j+1<<" column: "; //entering each element of the array
cin>>matrix[i][j];
}
}
}
void calculate(int n, int m, int matrix[10][10], double sum, double avg[10], int k) {
for (int i=0; i<n; i++) {
k=0;
sum=0;
avg=0;
for (int j=0; j<m; j++) {
if (matrix[i][j]>0) {
sum+=static_cast<double>(matrix[i][j]);
k++;
}
}
if (k>0) {
avg[i]=sum/static_cast<double>(k);
}
}
}
void results(double avg[10], int n) {
for (int i=0; i<n; i++) { //
cout<<"Average of "<<i<<" row is equal to: "<<avg[i]<<"\n";
}
}
答案 0 :(得分:2)
您不会更改n
中的m
和main()
。 input()
通过值接收参数,这意味着它创建一个副本,因此函数中所做的更改仅对函数是本地的。要解决此问题,只需通过引用传递n
和m
。
void input(int& n, int& m, int matrix[10][10])
答案 1 :(得分:2)
您的代码存在多个问题:
您询问用户数组的大小,但是您使用常量大小定义了数组:
int matrix[10][10];
如果用户输入11,会发生什么?这将导致未定义的行为。如果您想拥有真正的动态数组,请考虑使用std::vector。
当您在n
程序中阅读m
,void input(int n, int m, int matrix[10][10])
值时,您正在更改这些变量的副本(即由值传递,因此,更改仅对函数内部可见。当您离开该功能的范围时,您对它们所做的所有更改都将丢失。您需要通过引用传递这些参数,即:
void input(int& n, int& m, int matrix[10][10]);
这样,编译器就不会复制了,你将从你的main中更改相同的变量。
考虑到这一点,您需要以类似的方式更改calculate
程序:
void calculate(int n, int m, int matrix[10][10], double& sum, double avg[10], int& k);
不需要通过引用传递变量n
和m
,因为在这种情况下,它们是输入参数,不需要更改。