流程图算法 |从数组中查找 Cpp 中的矩阵
Flowchart Algorithm | Find Matrix in Cpp from Array
我遇到过这个关于算法主题的练习,使用流程图分别呈现和测试矩阵行的总和。
The Exercise with Matric
0
1
-2
-2
2
5
1
3
-1
到现在我还不会用Flowchart计算矩阵,大家能帮帮我吗?如果您使用 Flowgorithm 应用程序或任何其他类似应用程序来执行此操作,那就太好了。
结果应该是:
对于第一行:-1
第二个:5
第三个:3
我是这样做的,但是不知道怎么优化代码:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int rreshti[9] = {
0, 1, -2,
-2, 2, 5,
1, 3, -1,
};
int r1, r2, r3;
r1 = 0;
r2 = 0;
r3 = 0;
for(int i = 0; i <= 2; i++) {
r1 = r1 + rreshti[i];
};
cout << "Totali i reshtit te pare: " << r1 << endl;
for (int i = 3; i <= 5; i++) {
r2 = r2 + rreshti[i];
};
cout << "Totali i reshtit te pare: " << r2 << endl;
for (int i = 6; i <= 8; i++) {
r3 = r3 + rreshti[i];
};
cout << "Totali i reshtit te pare: " << r3 << endl;
return 0;
}
您可以像在二维矩阵中那样使用嵌套循环。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int no_of_rows = 3; // I would reccommend you to replace constants and use variables like this.
int no_of_cols = 3;
int rreshti[no_of_rows * no_of_cols] = {
0, 1, -2,
-2, 2, 5,
1, 3, -1,
};
vector<int> rowSum(no_of_rows, 0);
for(int i = 0; i < no_of_rows; i++){
for(int j = 0; j < no_of_cols; j++){
rowSum[i] += rreshti[i*no_of_cols + j];
}cout<<"Sum of row no. "<<(i+1)<<" is = "<<rowSum[i]<<endl;
}
return 0;
}
我遇到过这个关于算法主题的练习,使用流程图分别呈现和测试矩阵行的总和。
The Exercise with Matric
0 | 1 | -2 |
-2 | 2 | 5 |
1 | 3 | -1 |
到现在我还不会用Flowchart计算矩阵,大家能帮帮我吗?如果您使用 Flowgorithm 应用程序或任何其他类似应用程序来执行此操作,那就太好了。
结果应该是: 对于第一行:-1 第二个:5 第三个:3
我是这样做的,但是不知道怎么优化代码:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int rreshti[9] = {
0, 1, -2,
-2, 2, 5,
1, 3, -1,
};
int r1, r2, r3;
r1 = 0;
r2 = 0;
r3 = 0;
for(int i = 0; i <= 2; i++) {
r1 = r1 + rreshti[i];
};
cout << "Totali i reshtit te pare: " << r1 << endl;
for (int i = 3; i <= 5; i++) {
r2 = r2 + rreshti[i];
};
cout << "Totali i reshtit te pare: " << r2 << endl;
for (int i = 6; i <= 8; i++) {
r3 = r3 + rreshti[i];
};
cout << "Totali i reshtit te pare: " << r3 << endl;
return 0;
}
您可以像在二维矩阵中那样使用嵌套循环。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int no_of_rows = 3; // I would reccommend you to replace constants and use variables like this.
int no_of_cols = 3;
int rreshti[no_of_rows * no_of_cols] = {
0, 1, -2,
-2, 2, 5,
1, 3, -1,
};
vector<int> rowSum(no_of_rows, 0);
for(int i = 0; i < no_of_rows; i++){
for(int j = 0; j < no_of_cols; j++){
rowSum[i] += rreshti[i*no_of_cols + j];
}cout<<"Sum of row no. "<<(i+1)<<" is = "<<rowSum[i]<<endl;
}
return 0;
}