我需要在C#上创建此特定形状的帮助
链接到形状为https://drive.google.com/file/d/1-5xzVHPm8xG4wvkcGgtZ4IBx2uSgwS4u/view?usp=sharing的图像
我已经尝试制作这种形状很长时间了,但是似乎无法正确地制作出我目前刚刚编码的相同图案的两次连续打印的代码。
using System;
namespace Patterns
{
class Program
{
static void Main(string[] args)
{
int i, j, k;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= 6 - i; j++)
{
Console.Write("*");
}
for (k = 1; k < i; k++)
{
Console.Write(" ");
}
for (j = 1; j <= 6 - i; j++)
{
Console.Write("*");
}
Console.Write("\n");
}
for (i = 2; i <= 5; i++)
{
for (j = 1; j <= i; j++)
{
Console.Write("*");
}
for (k = 1; k <= 5 - i; k++)
{
Console.Write(" ");
}
for (j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}
}
答案 0 :(得分:1)
哇,那是一大堆不可读的代码:)我想我们需要简化一下:
int numOfStars = 5;
int numOfSpace = 2;
while(numOfStars > 0){
Console.Write(new string('*', numOfStars));
Console.Write(new string(' ', numOfSpace));
Console.WriteLine(new string('*', numOfStars));
numOfStars--;
numOfSpace+=2;
}
numOfStars = 2;
numOfSpace = 8;
while(numOfStars < 6){
Console.Write(new string('*', numOfStars));
Console.Write(new string(' ', numOfSpace));
Console.WriteLine(new string('*', numOfStars));
numOfStars++;
numOfSpace-=2;
}
模式是一百种不同的方法,这里的对象课程是:
答案 1 :(得分:1)
这是另一种做到这一点的方法:
public static void DrawShape(int maxStars)
{
int lineLength = maxStars * 2 + 2;
for (int row = 0; row < lineLength - 1; row++)
{
int starCount = maxStars - row;
if (starCount == 0 || starCount == -1) continue; // This is the hackey line
if (starCount < 0) starCount *= -1;
int spaceCount = lineLength - starCount * 2;
string stars = new string('*', starCount);
string spaces = new string(' ', spaceCount);
Console.WriteLine(stars + spaces + stars);
}
}
答案 2 :(得分:1)
暴力手段。一种简单的方法,它带有两个参数,一个用于一行上的空格数,第二个参数用于编写“ *”字符数……
private static void WriteCharacters(int numSpaces, int numChars) {
Console.Write(new string('*', numChars));
Console.Write(new string(' ', numSpaces));
Console.Write(new string('*', numChars));
Console.WriteLine();
}
然后,写下所有九行...
static void Main(string[] args) {
WriteCharacters(2, 5);
WriteCharacters(4, 4);
WriteCharacters(6, 3);
WriteCharacters(8, 2);
WriteCharacters(10, 1);
WriteCharacters(8, 2);
WriteCharacters(6, 3);
WriteCharacters(4, 4);
WriteCharacters(2, 5);
Console.ReadKey();
}