zoukankan      html  css  js  c++  java
  • 6、C#基础整理(for 语句经典习题--for循环嵌套、穷举)

    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             } 
  • 相关阅读:
    L3-015. 球队“食物链”【DFS + 剪枝】
    L3-002. 堆栈【主席树 or 线段树 or 分块】
    PTA L1-006 连续因子【暴力模拟】
    【路由和交换之H3C自导自演】
    【ospf-stub区域配置】
    【ospf-链路验证】
    【ospf-vlink虚拟连接】
    【c学习-14】
    【c学习-13】
    【php学习-5】
  • 原文地址:https://www.cnblogs.com/wleaves/p/4169929.html
Copyright © 2011-2022 走看看