6、C#基礎整理(for 語句經典習題--for迴圈嵌套、窮舉)

來源:互聯網
上載者:User

標籤:style   blog   ar   color   sp   for   strong   on   檔案   

1、for迴圈嵌套----最基礎題目:求階乘的和

 int sum = 0; int n = int.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) {      int sum1 = 1;//定義變數sum1,每次迴圈都賦予其初始值1,求階乘專用      for (int j = 1; j <= i+1; j++)      {           sum1 = sum1 * j;      }      sum = sum + sum1;//將每次階乘的和相加 } Console.WriteLine(sum);

2、for迴圈的窮舉

例:100元買2元的鉛筆,5元的鉛筆盒,10元的檔案夾,15元的彩筆,剛好花光,每樣物品必須有一種,一共有多少種可能性?

int count = 0;for (int qb = 1;qb<50;qb++){     for (int he = 1; he < 20; he++)     {            for (int jia = 1; jia < 10; jia++)            {                 for (int cai = 1; cai < 7;cai++ )                 {                      if (qb * 2 + he * 5 + jia*10+cai*15== 100)                      {                           count++;                           Console.WriteLine("鉛筆:{0},鉛筆盒:{1},檔案夾:{2},彩筆:{3}", qb, he,jia,cai);                       }                  }             }       }}Console.WriteLine(count);    

3、用 for 迴圈的嵌套列印一個菱形

 1             Console.WriteLine("請輸入邊長:"); 2             int ii = int.Parse(Console.ReadLine()); 3             Console.WriteLine("列印出來的菱形為:"); 4             //列印上面的三角形 5             for (int g = 0; g < ii; g++) 6             { 7                  8                 for (int n = ii - g; n > 1; n--) 9                 {10                     Console.Write("  ");11                 }12                 for (int m = 1; m <= g; m++)13                 {14                     Console.Write(" #");15                 }16                17                 for (int p = 1; p <= g; p++)18                 {19                     Console.Write(" #");20                 }21                 Console.WriteLine(" #");22             }23             //列印下面的三角形24             for (int j = 0; j < ii - 1; j++)25             {26                 for (int a = 1; a <= j + 1; a++)27                 {28                     Console.Write("  ");29                 }30                 for (int b = ii - j; b > 2; b--)31                 {32                     Console.Write(" #");33                 }34                 for (int c = ii - j; c > 2; c--)35                 {36                     Console.Write(" #");37                 }38                 Console.WriteLine(" #");39             } 

 

6、C#基礎整理(for 語句經典習題--for迴圈嵌套、窮舉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.