简体   繁体   English

C++ 矩阵值

[英]C++ Matrix values of

I want to create a matrix of 5 lines and 5 columns which contains values from 1 to 9. The following programs displays numbers from 1 to 25 instead, when I input 5 to the program..我想创建一个包含 5 行和 5 列的矩阵,其中包含 1 到 9 的值。当我向程序输入5时,以下程序将显示 1 到 25 之间的数字。

#include <iostream>

using namespace std;

int a[20][20], n, x = 0;

int main()
{
    cout << "n=";
    cin >> n;

    for(int i=1; i<=n; i++)
    for(int j=1; j<=n; j++)
    {
        a[i][j] = x+1;
        x = x+1;
    }

    for(int i=1; i<=n; i++)
    {
        for(int j=1; j<=n; j++)
            cout << a[i][j] << " ";

        cout << endl;
    }
}

I'm a c++ beginner, so maybe it's simple to do but i don't know how to make it show values from 1 to 9. This is the matrix I except:我是一个 c++ 初学者,所以也许这很简单,但我不知道如何让它显示从 1 到 9 的值。这是我除了的矩阵:

1 2 3 4 5
6 7 8 9 1
2 3 4 5 6 
7 8 9 1 2
3 4 5 6 7 

You need to use the modulus operator (%).您需要使用模运算符 (%)。 If you want the values in the matrix to be as you have computed them, but only need to change the display, you would output the matrix values as follows:如果您希望矩阵中的值与您计算出来的一样,但只需要更改显示,您可以按如下方式输出矩阵值:

cout << (a[i][j] % 10) << " ";

If you want the one-digit values to be in the matrix itself, you would instead change the increment on 'x' to the following:如果您希望矩阵本身包含一位数的值,则应将“x”上的增量更改为以下内容:

x = (x+1) % 10;}

There are some issues in your code.您的代码中存在一些问题。

C arrays or STL containers? C 数组或 STL 容器?

First off, a your matrix may only hold matrices as big as 20x20.首先, a你的矩阵可只持有矩阵一样大的20×20。 Your program will silently fail if you enter n bigger than 20, because you will access memory out of bounds;如果您输入的n大于 20,您的程序将无声地失败,因为您将越界访问内存; which causes an undefined behavior (see other common UB cases here ).这会导致未定义的行为(请参阅此处的其他常见 UB 案例)。

You may want to use a dynamic size array - A good way to achieve this is to use std::vector .您可能想要使用动态大小数组 - 实现此目的的一个好方法是使用std::vector Unfortunately, this isn't as comfortable to use as a C-style array with two dimensions - you can achieve the same access syntax using a std::vector<std::vector<int>> , but this is not very efficient (see this answer if you are interested why) nor quite comfortable.不幸的是,这不像具有二维的 C 样式数组那样方便使用 - 您可以使用std::vector<std::vector<int>>实现相同的访问语法,但这不是很有效(如果您有兴趣,请参阅此答案为什么)也不太舒服。

The Boost C++ library provides a multidimensional array library . Boost C++ 库提供了一个多维数组库 Once you get experienced enough, you may find an use in it.一旦你有足够的经验,你可能会发现它的用处。

<= or < ? <=< ? 0 -index or 1 -indexed? 0索引还是1索引?

Many programming languages today uses 0 -indexing for arrays.今天许多编程语言对数组使用0索引。 This means the first element of the array is located at index 0 , not 1 .这意味着数组的第一个元素位于索引0 ,而不是1 Some languages, such as Lua, doesn't do this.某些语言,例如 Lua,不会这样做。

This means you should iterate i and j from 0 to n .这意味着您应该从0n迭代ij This also means n is excluded, so you should use < , not <= .这也意味着n被排除在外,因此您应该使用< ,而不是<=

Filling the matrix with numbers from 1 to 9用 1 到 9 的数字填充矩阵

Your code doesn't do anything so you get numbers from 1 to 9 - it only fills the matrix with numbers from 1 to n * n .您的代码不执行任何操作,因此您会得到 1 到 9 之间的数字 - 它仅使用 1 到n * n数字填充矩阵。 You could change this using an if clause to set x every time it goes above 9 :您可以使用if子句更改此设置以在每次超过9时设置x

if (x > 9) { x = 0; } // x = 0 because it will be 1 on the next iteration

That being said, there is more convenient, as @PMar's answer says.话虽如此,正如@PMar 的回答所说,还有更方便的方法。 The modulo operator % will do the task as well.模运算符%也将完成任务。

a[i][j] = (x % 9) + 1;
x = (x % 9) + 1;

This way, you will get every number from 1 to 9 .这样,您将获得从19每个数字。

Now, you can also do another cleanup: Why are you calculating x 's next value, and only then setting it?现在,您还可以进行另一次清理:为什么要计算x的下一个值,然后才设置它? You could assign the new x value before the assignment to your matrix's cell.您可以在分配给矩阵的单元格之前分配新的x值。 This allows having clearer code, with less copy pasting, which implies better maintainability.这允许拥有更清晰的代码,更少的复制粘贴,这意味着更好的可维护性。

x = (x % 9) + 1;
a[i][j] = x;

Another code quality consideration另一个代码质量考虑

I cannot say if your original code source was indented like your question (before it was edited), but you should really indent your code, for the future you and other people that will have to read your code.我不能说你的原始代码源是否像你的问题一样缩进(在编辑之前),但你真的应该缩进你的代码,为了将来你和其他人必须阅读你的代码。 It allows for much better readability.它允许更好的可读性。

Same goes for different parts of your code : Add some space!代码的不同部分也是如此:添加一些空间! It only can get more readable if you make a clear distinction between even just expressions.只有在甚至只是表达式之间进行明确区分时,它才能变得更具可读性。

#include <iostream>

int main()
{

    int a[5][5];
    int x = 1;

    for(int i = 0; i < 5; i++)
    {
        for(int j = 0; j < 5; j++)
        {
            if(x > 9)
                x = 1;
            a[i][j] = x;
            x++;
        }
    }

    for(int i = 0; i < 5; i++)
    {
        for(int j = 0; j < 5; j++)
        {
            if(a[i][j] < 10)
                std::cout << " ";
            std::cout << a[i][j] << " ";
        }

        std::cout << std::endl;
    }

    std::cout << std::endl;
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM