【发布时间】:2019-09-04 05:58:50
【问题描述】:
我有一个学习 C++ 的 CS 课程的作业。对于这个任务,我必须编写一个可以传递给函数的二维字符数组。该数组必须由 50 行和 50 列组成。所有元素都必须初始化为空格(' ')。
我在这里创建了数组我还编写了一个 for 循环来将数组放置在网格中。现在,我必须将星号随机分配给数组的元素,这些元素仍然是空白的,我不知道该怎么做。
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
#include <stdlib.h>
using namespace std;
int main()
{
const int rows = 50; // Variables
const int col = 50;
const char SIZE = ' ';
const int hgt = 48;
int X = rand() % 50; // *Edited: This code was copied from an older save
int y = rand() % 50;
char board[rows][col]; // Array initialization
int i;
int j;
int x;
srand((unsigned)time(0));
for (i = 0; i < rows; i++) // For loop to place array in grid.
{
for (j = 0; j < col; j++)
{
board[i][j] = SIZE;
}
board[x][y] = '*'
}
cout << setfill('-') << setw(50) << "" << endl; // Grid
for (X = 0; X < hgt; X++)
{
cout << "|" << setfill(' ') << setw(49) << "|" << endl;
}
cout << setfill('-') << setw(50) << "" << endl;
cin.ignore();
cout << "Press Enter to continue..." << endl;
cin.ignore();
return 0;
}
数组有效,网格有效。我只是不知道如何分配随机放置在网格中的星号以及如何将该数组传递给函数。
【问题讨论】:
-
为什么
board[x][y] = '*'在for里面?它总是做同样的事情,没有必要重复它。另外,在“打印”地图时,为什么不使用数组的值?至于放置星号,您可以使用一个星号。如果您需要更多添加循环。 -
将初始填充字符称为“SIZE”是很奇怪的。在什么方面你觉得它是一个大小? (单词的含义不会因为涉及计算机而消失。说你的意思;说你想说的。)
-
您用 c++ 标记了这个问题,但您使用的是 c 编码风格。使用std::array、range based for loops、<random> 和<algorithm>。
-
不要使用using namespace std。不要同时包含
<cstdlib>和include <stdlib.h>。选择一个 -
好点。您可以(也可以不)推荐您的老师观看此视频Stop Teaching C。 ;-) 我必须承认我首先学习了 C(几十年前),后来又转向了 C++(几十年前),恐怕我还在学习。很难将 C 习惯留在 C++ 中,因为他们中的大多数人仍在使用 C++(不知何故)......
标签: c++ function multidimensional-array