我想学习如何打印钻石如下:我是初学者,非常感谢帮助
给一封信打印一颗钻石,以' A' 最宽处提供的信件。
例如:print-diamond' E'打印
A
B B
C C
D D
E E
D D
C C
B B
A
例如:print-diamond' C'打印
A
B B
C C
B B
A
答案 0 :(得分:1)
实际上,您的代码有两个错误(我没有考虑代码和算法的效率)。
首先:在构建菱形时,for循环不应该是for (int i = 0; i < letter_number + i; i++)
而是for (int i = 0; i <= letter_number; i++)
。
第二:当您绘制菱形时 - 变量j
应该被置于循环之外,您应该使用WriteLine
而不是Write
。
例如,绘制部分代码可能是这样的:
Console.WriteLine();
int jj = 1;
for (int i = 0; i < 2 * letter_number + 1; i++)
{
if (i < letter_number + 1)
Console.WriteLine(diamond[i]);
else
{
Console.WriteLine(diamond[i - 2 * jj]);
jj++;
}
}
旁注: int letter_number;
应初始化为int letter_number = 0;
或类似的内容,因为您在条件下分配了它的值,而不是在代码后面的每种情况下,实际上你提供的代码甚至在没有这种显式初始化的情况下也不会编译。
答案 1 :(得分:0)
试试这个。经过测试的工作。
using System;
namespace ConsoleApplication
{
internal class Program
{
private static void Main(string[] args)
{
char[] letter = new char[26]
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z'
};
int letter_number = 0;
//array of strings
string[] diamond = new string[52];
//get the letter
Console.WriteLine("User enters a Letter between A and Z ");
char user_letter = Console.ReadKey().KeyChar;
Console.WriteLine("");
//search for letter number in the array letter
for (int i = 0; i < letter.Length; i++)
{
if (letter[i] == user_letter)
{
letter_number = i;
break;
}
}
//construct diamond
for (int i = 0; i <= letter_number; i++)
{
//add initial spaces
for (int j = 0; j < letter_number - i; j++)
{
diamond[i] += " ";
}
//add letter (first time)
diamond[i] += letter[i];
//add space between letters
if (letter[i] != 'A')
{
for (int j = 0; j < 2*i - 1; j++)
{
diamond[i] += " ";
}
//add letter (second time)
diamond[i] += letter[i];
}
// Draw the first part of the diamond as it's composing.
Console.WriteLine(diamond[i]);
}
for (int i = letter_number - 1; i >= 0; i--)
{
// Draw the second part of the diamond
// Writing the diamondArray in reverse order.
Console.WriteLine(diamond[i]);
}
// Mark a pause
Console.ReadKey();
}
}
}
输出:
User enters a Letter between A and Z
K
A
B B
C C
D D
E E
F F
G G
H H
I I
J J
K K
J J
I I
H H
G G
F F
E E
D D
C C
B B
A