第十六节 流程控制 六
do while循环
do
{
//循环体
}
while(循环条件);
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HE { class Program { static void Main(string[] args) { int i = 1; int sum = 0; do { sum = sum + i; i++; } while(sum<=2005); Console.WriteLine("i={0}", i - 1); } } }
for循环
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HE { class Program { static void Main(string[] args) { int sum = 0; for (int i = 1; i <= 100; i++) { sum = sum + i; } Console.WriteLine("sum={0}",sum); } } }
for语句计算阶乘
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HE { class Program { static void Main(string[] args) { int n = Convert.ToInt32(Console.ReadLine()); int cc = 1; for (int i = 1; i <=n; i++) { cc *= i;//cc=cc*n } Console.WriteLine("{0}!={1}",n,cc); } } }
break:语句跳出循环体
continue 语句:中断本圈循环
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Xunhuan { class Program { static void Main(string[] args) { //break for (int i = 123; i <= 10000; i++) { if ((i % 123 == 0) && (i % 76 == 0)) { Console.WriteLine(i); break; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace c { class Program { static void Main(string[] args) { //continue for (int i = 1; i < 10; i++) { if (i % 2 == 0) { continue; } Console.WriteLine(i); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace qiantao1 { class Program { static void Main(string[] args) { int x = 0, y, z = 0; while (x < 100) { y = 0; while(y<100) { z = 100 - x - y; if (5 * x + 3 * y + z / 3 == 100) Console.WriteLine("x={0} y={1} z={2}", x, y, z); y = y + 1; } x = x + 1; } } } }
C#勾股定理
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Gougu { class Program { static void Main(string[] args) { for(int a=1;a<100;a++) { for (int b = 1; b < 100; b++) { for (int c = 1; c < 100; c++) { if (a * a + b * b == c * c) Console.WriteLine("a={0},b={1},c={2}", a, b, c); } } } } } }