//调用函数时,三次出现“无法绘制形状”的错误 //在if和for循环中应该改变什么,以便当高度或宽度小于1时,它应该说“不能绘制形状”。 你可以在代码中看到,当高度为1,宽度为5时,显示“无法绘制”。
这是我在C#中的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class ShapeDrawer {
public static string DrawSquare(int height, int width) {
//在这里绘制正方形的代码
string s = "";
string wrong = "Cannot draw that shape.";
//条件如果宽度和高度小于1则应打印无法绘制
}if (width < 1 || height < 1) {
return wrong;
} else {
//nested for loops to check the condition
for (int i = 1; i <= height; i++) {
for (int j = 1; j <= width; j++) {
if (i == 1 | j == 1 || i == height || j == width) {
if (width <= 1 || height <= 1) {
s = s + "Cannot draw that shape.";
} else {
//print asterisk if condition is true
s = s + "*";
}
} else {
s = s + " ";
}
}
s = s + "\n";
}
return s;
}
//打印等腰三角形
public static string DrawIsoscelesTriangle(int size) {
//code to draw the triangle
string s = "";
string wrong = "Cannot draw that shape.";
for (int i = 1; i <= size; i++) {
for (int j = 1; j <= i; j++) {
s = s + "*";
}
s = s + "\n";
}
for (int i = size - 1; i >= 1; i--){
for (int j = 1; j <= i; j++){
s = s + "*";
}
s = s + "\n";
}
//如果三角形的大小小于2则打印无法绘制
if (size < 2) {
return wrong;
} else {
return s;
}
}
}
class Program {
//主要调用函数
static void Main() {
//带高度和宽度的方形输入
Console.WriteLine(ShapeDrawer.DrawSquare(1, 5));
//方形的输入,大小为2
Console.WriteLine(ShapeDrawer.DrawIsoscelesTriangle(2));
Console.WriteLine("\n\n Hit Enter to exit.");
Console.ReadLine();
}
}