我需要帮助完成这个任务。

我已经尝试了一些东西,我可以包括到目前为止我写的代码。
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int i, j, n;
cout << "Please enter the positive integer:";
cin >> n;
if (n < 0) {
cout << "\nEntered integer is not positive! Please enter the positive integer:";
cin >> n;
}
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
if (i == 1 || i == n || j == 1 || j == n) {
cout << setw(n) << "*";
}
else {
cout << setw(n) << " ";
}
}
cout << endl << "\n";
}
return 0;
}提前感谢!
发布于 2022-09-23 03:04:03
在您的实现中有几个问题:
if (n < 0) {
cout << "\nEntered integer is not positive! Please enter the positive integer:";
cin >> n;
}上述条件将只验证用户输入一次。如果用户输入负数不止一次,则不会检查它。
cout << endl << "\n";这将导致行的两端被打印,这是不需要的。
以下是完成所需工作的工作程序:
int main()
{
int n;
cout << "Please enter the positive integer: ";
cin >> n;
while (n < 0) {
cout << "\nEntered integer is not positive! Please enter the positive integer: ";
cin >> n;
}
for (int i = 0; i <= (n*n); i++) {
for (int j = 0; j <= (n*n); j++) {
if (i == 0 || (i % n == 0) || (j == 0) || (j % n == 0)) {
cout << setw(2) << "*";
} else {
cout << setw(2) << " ";
}
}
cout << '\n';
}
return 0;
}下面是程序的输出:

发布于 2022-09-22 22:36:07
假设1x1网格如下所示:
****
* *
* *
****例如,也不依赖于输入的数字,我将使用以下内容:
for (int i = 0; i < n * 3 + 1; ++i) {
cout << "*"; //First row with stars
}
cout << endl;
for (int i = 0; i < n; ++i) {
cout << "*"; //First column with stars
for (int j = 0; j < n; ++j) {
cout << " *"; //Empty box and closing star
}
cout << endl;
cout << "*"; //First column with stars
for (int j = 0; j < n; ++j) {
cout << " *"; //Empty box and closing star
}
cout << endl;
for (int j = 0; j < n * 3 + 1; ++j) {
cout << "*"; //Bottom row of box with stars
}
cout << endl;
}这段代码没有经过测试,只是快速输入,可能无法工作,所以要小心使用它。如果有什么问题请告诉我。
https://stackoverflow.com/questions/73821188
复制相似问题