【问题标题】:Flowchart Algorithm | Find Matrix in Cpp from Array流程图算法 |从数组中查找 Cpp 中的矩阵
【发布时间】:2021-06-05 10:12:50
【问题描述】:

我遇到了这个关于算法主题的练习,使用流程图分别呈现和测试矩阵行的总和。

The Exercise with Matric

0 1 -2
-2 2 5
1 3 -1

直到现在,我都不知道用流程图计算矩阵,你们能帮我吗?如果您使用 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;
}

【问题讨论】:

  • 你知道什么是流程图吗?你能用英语描述如何计算第一行吗?但是,更重要的是,到目前为止你做了什么?
  • @AlessandroTeruzzi 我做到了,请检查。
  • 您的代码运行良好。它给出了预期的结果。你还想实现什么?
  • @ArminMontigny 我只是想优化它。

标签: c++ c algorithm math flowchart


【解决方案1】:

您可以像在二维矩阵中一样使用嵌套循环。

#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;
}

【讨论】:

  • 我们也可以用多维数组来做到这一点?像 rreshti[3][3]!不过谢谢!
  • 是的。理想情况下,您会希望使用多维数组,因为它们很容易理解。但是您将其声明为一维数组,所以我想,这可能是您从某个地方获得的输入,并且无法将其更改为二维数组。
  • 谢谢你risingStart,很好的解决方案!
  • @withakeyboard 我的荣幸 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-19
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
  • 2020-05-12
相关资源
最近更新 更多