在这里,我编写了一个使用 2 维数组并打算执行行和的 C++ 代码,但它没有给出正确的输出
Here i have written a C++ code which uses 2-dimension array and meant to perform rowsum but it is not giving proper output
# include<iostream>
using namespace std;
int const rows=3; //rows are kept constant
int const cols=3; //columns are kept constant
void display(int arr[][cols],int rows,int cols); //function prototype
int rowsum(int arr[][cols],int rows,int cols); //function prototype
int main()
{
int z [rows][cols]; //2-D array declaration
int r,c;
for(r=0;r<rows;r++)
{
for(c=0;c<cols;c++)
{
cout<<"Enter elements of array["<<r<<"]["<<c<<"]:";
cin>>z[r][c];
}
}
display(z,rows,cols); //Function call
rowsum(z,rows,cols); //Function call
return 0;
}
void display(int arr[][cols],int rows,int cols) //function to display input
{
int r,c;
for(r=0;r<rows;r++)
{
for(c=0;c<cols;c++)
{
cout<<"Elements of array["<<r<<"]["<<c<<"]="<<arr[r][c]<<endl;
}
}
}
int rowsum(int arr[][cols],int rows,int cols) //Function to perform rowsum
{
int c,sum=0,r=0;
for(c=0;c<cols;c++)
{
sum=sum+arr[r][c];
cout<<"the sum of rows is:"<<sum<<endl;
}
return sum;
}
上面是一个使用 2-D 数组的C++代码。它接受用户的输入,并使用显示功能显示该输入。输入后,我想对行求和,为此我编写了一个名为rowsum的函数,但它无法正常工作。它不提供所需的输出。
代码的问题在于您在这里使用了单个循环,而不是所需的两个 for 循环。因此,您的代码所做的只是简单地计算第 0 行的总和(自 r=0
年以来(。
您实际需要做的是计算一行的总和(即 for(c=0;c<cols;c++)
(,row
次数。嗷!!
for(r=0;r<rows;r++)
{
sum = 0;
for(c=0;c<cols;c++) //calculates sum of rth row
{
sum += arr[r][c];
}
cout<<"Sum of row " << i <<" is " << sum ;
}
这是因为您打印出了第一行的部分总和。
您应该有两个循环,一个用于行,一个用于列,并且仅在遍历所有列后打印出结果。
或者,如果您只需要设置行的总和,则至少将 print 语句移出循环,以便只获得最终总和,而不是中间结果。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么在这个代码结束循环中没有得到结束
- 在c代码之间共享数据的最佳方式
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值