循环嵌套练习题
//BOSS://讓用戶輸入一個(gè)奇數(shù),打印菱形,最長(zhǎng)的行內(nèi)容個(gè)數(shù)為用戶輸入的個(gè)數(shù),并且由英文字母拼接而成//比如用戶輸入了7// A// ABA// ABCBA// ABCDCBA// ABCBA// ABA// A//1、接收并判斷用戶輸入的是不是數(shù)字 try{#region 解法一//Console.Write("請(qǐng)輸入一個(gè)奇數(shù):");//int a = Convert.ToInt32(Console.ReadLine());//if (a % 2 != 0)//{// for (int i = 1; i <= (a + 1) / 2; i++)// {// for (int b = 1; b <= ((a + 1) / 2 - i); b++)// {// Console.Write(" ");// }// char c = 'A';// for (int d = 1; d < i; d++)// {// Console.Write(c);// c++;// }// for (int e = 1; e <= 26; e++)// {// Console.Write(c);// if (c == 'A')// {// break;// }// c--;// }// Console.WriteLine();// }// for (int i = 1; i < (a + 1) / 2; i++)// {// for (int b = 1; b <= i; b++)// {// Console.Write(" ");// }// char c = 'A';// for (int d = 1; d < (a + 1) / 2 - i; d++)// {// Console.Write(c);// c++;// }// for (int e = 1; e <= 26; e++)// {// Console.Write(c);// if (c == 'A')// {// break;// }// c--;// }// Console.WriteLine();// }//}#endregion#region 解法二 上半部分 Console.Write("請(qǐng)輸入一個(gè)奇數(shù):");int a = Convert.ToInt32(Console.ReadLine());if (a % 2 != 0)//是奇數(shù),執(zhí)行這個(gè)if里面的代碼
{for (int i = 1; i <= (a + 1) / 2; i++)//上半部分行數(shù),(a+1)/2 代表 上半部分需要打印的行數(shù)。
{char ch = 'A';string end = "";int b = ((i * 2 - 1) + 1) / 2 - 1;//開始 -- 的數(shù)值bool isok = false;int count = 0;for (int j = 1; j <= ((a + 1) / 2) - i; j++)//拼接每行打印的空格數(shù)
{end += " ";}for (int j = 1; j <= i * 2 - 1; j++)//拼接每行打印的字母數(shù)
{end += ch;if (count == b)//判斷是不是該 -- 了
{isok = true;}if (isok)//滿足條件,執(zhí)行這個(gè) if 里面的代碼
{if (ch == 'A'){ch = 'Z';}else//條件不成立
{ch--;}}else{if (ch == 'Z'){ch = 'A';}else{ch++;}count++;}}Console.WriteLine(end);}}#endregion#region 解法二 下半部分for (int i = 1; i < (a + 1) / 2; i++){char ch = 'A';string end1 = "";int b = ((a - i * 2) + 1) / 2 - 1;int count = 0;bool isok = false;for (int j = 1; j <= i; j++){end1 += " ";}for (int j = 1; j < (a - i * 2) + 1; j++){end1 += ch;if (count == b){isok = true;}if (isok){if (ch == 'A'){ch = 'Z';}else{ch--;}}else{if (ch == 'Z'){ch = 'A';}else{ch++;}count++;}}Console.WriteLine(end1);}#endregion}catch{Console.WriteLine("輸入有誤!");}Console.ReadLine();
?
轉(zhuǎn)載于:https://www.cnblogs.com/123lucy/p/5523144.html
總結(jié)
- 上一篇: PHP-02.文件上传、php保存/转移
- 下一篇: Bootstrap(导航条)