编程实践5-9
课程元素类型 任务
打印菱形
比如输入一个数字 必须为奇数 表示要输出几行星号,组成的菱形。
输入5
则输出结果为
我会告诉你我做了两个钟头么。这个其实如果不用二维数组做也没那么难想,关键老师要求用二维数组做。
然后老师指导了下才最终做出来。
老师的知道思想是,分成两部分来赋值,上半部和和下半部分。
上半部分 n/2 +i n/2-j 都要赋值
下半部分是n/2-i 个空格
我做的时候只写了上半部分。然后输出的时候反向输出了一次就完成了下半部分。
不经常写总结,语言可能不容易理解。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace sj_5_9 { class Program { static void Main(string[] args) { int iA, i, j; char[,] chA; Console.Write("请输入菱形的层数(奇数):"); iA = Convert.ToInt32(Console.ReadLine()); chA = new char[iA, iA]; for (i = 0; i <= chA.GetLength(0) / 2; i++) { for (j = 0; j <= i; j++) { chA[i, chA.GetLength(0) / 2 - j] = '*'; chA[i, chA.GetLength(0) / 2 + j] = '*'; } } for (i = 0; i <= chA.GetLength(0) / 2; i++) { for (j = 0; j <= chA.GetLength(1) - 1; j++) { Console.Write(chA[i, j]); } Console.WriteLine(); } for (i = chA.GetLength(0) / 2 - 1; i >= 0; i--) { for (j = 0; j <= chA.GetLength(1) - 1; j++) { Console.Write(chA[i, j]); } Console.WriteLine(); } Console.ReadKey(true); } } }