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 }
时间: 2024-10-10 10:56:13