简体   繁体   English

使用函数 (C++) 创建一个 10x10 矩阵,其中填充了 1 - 99 的随机整数

[英]Create a 10x10 matrix filled with random integers from 1 - 99 using functions (C++)

I am writing some code that has 2 functions.我正在编写一些具有 2 个功能的代码。 The first function I believe has no problems.第一个function相信没有问题。 The first one is to create the 10x10 matrix filled with random numbers, the second function is to print the matrix.第一个是创建填充随机数的 10x10 矩阵,第二个 function 是打印矩阵。 The problem that I am having is that even with the declaration of the row and column sizes, the matrix prints out in one line and not in a grid-like shape.我遇到的问题是,即使声明了行和列大小,矩阵也会打印在一行中,而不是网格状。 I have tried to use the setw to end the line when the limit reaches 10. I am new to programming so I am not sure why the array is not printing the way it should.当限制达到 10 时,我尝试使用 setw 结束行。我是编程新手,所以我不确定为什么数组没有按应有的方式打印。

This is the code I have:这是我的代码:

#include <iostream>
#include <ctime>
#include <iomanip>
#include <cstdlib>

using namespace std;

const int ROW_SIZE = 10;
const int COLUMN_SIZE = 10;

void initialize(int [][10], int, int);
void display(int matrix[][10], int, int);

int main() {

    int matrix [ROW_SIZE][COLUMN_SIZE];

    initialize(matrix, ROW_SIZE, COLUMN_SIZE);

    display(matrix, ROW_SIZE,COLUMN_SIZE);


    return 0;
}


//question 1
void initialize(int matrix[][COLUMN_SIZE], int ROW_SIZE, int COLUMN_SIZE){
    for (int i = 0; i < ROW_SIZE; i++){
        for(int j = 0; j < COLUMN_SIZE; j++){
            matrix[i][j] =  1 + rand() % 99;
        }
    }
}

//question 2
void display(int matrix[][COLUMN_SIZE], int ROW_SIZE, int COLUMN_SIZE){
    for(int i = 0; i < ROW_SIZE; i++){
        for(int j = 0; j < COLUMN_SIZE; j++){
            cout<< setw(4)<<matrix[i][j]<< " ";
        }
    }
    cout<< endl;
}

The problem is that you're not ever printing an end of line character.问题是您永远不会打印行尾字符。 Setw(n) will tell cout that every chunk of text that you write has to be printed using exactly n characters, but it doesn't say that that chunk of text has to end in a newline. Setw(n) 会告诉 cout 你写的每一块文本都必须使用 n 个字符打印,但它并没有说那块文本必须以换行符结尾。

To make sure that there's a new line after every row of your matrix, you could write cout << endl, or cout << '\n' (a fancy character meaning "start a new line") after printing each row.为了确保矩阵的每一行之后都有一个新行,您可以在打印每一行之后编写 cout << endl 或 cout << '\n' (一个花哨的字符,意思是“开始新行”)。 Both of which explicitly tell the computer to add a new line.两者都明确告诉计算机添加新行。

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

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