.Net基础篇_学习笔记_第六天_for循环的嵌套_乘法口诀表
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace 第六天_for循环的嵌套 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 int num01; 14 int num02; 15 for (num01 = 1; num01 <= 9; num01++) 16 { 17 for (num02=1; num02 <= num01; num02++) 18 { 19 20 Console.Write("{0}*{1}={2}\t", num01, num02, num01 * num02); 21 if (num01 <= num02) 22 { 23 Console.Write("\n"); 24 } 25 } 26 27 28 } 29 Console.ReadKey(); 30 } 31 } 32 }
当某个事情要做一边,另外一个事情要做N遍的时候,需要用到for循环的嵌套。
优化为:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace 第六天_for循环的嵌套 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 int num01; 14 int num02; 15 for (num01 = 1; num01 <= 9; num01++) 16 { 17 for (num02=1; num02 <= num01; num02++) 18 { 19 Console.Write("{0}*{1}={2}\t", num01, num02, num01 * num02); 20 } 21 Console.WriteLine(); //Console.Write("\n"); 22 } 23 Console.ReadKey(); 24 } 25 } 26 }
引申:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace 第六天_for循环的嵌套 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 int num01; 14 int num02; 15 for (num01 = 1; num01 <= 9; num01++) 16 { 17 for (num02=1; num02 <= num01; num02++) 18 { 19 20 Console.Write("{0}*{1}={2}\t", num01, num02, num01 * num02); 21 22 if (num01 <= num02) 23 { 24 Console.Write("\n"); 25 break; //此处的break不起作用,在上面的for循环中起作用?为什么? 26 } 27 28 } 29 30 31 } 32 Console.ReadKey(); 33 } 34 } 35 }
附带:
加法表
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace 第六天_do_while循环 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 Console.WriteLine("请输入一个数字:"); 14 int num00=Convert.ToInt32(Console.ReadLine()); 15 Console.WriteLine("您得到的加法表为:"); 16 for (int i = 0; i<= num00; i++) 17 { 18 19 Console.WriteLine("{0}+{1}={2}", i, num00-i, num00); 20 21 } 22 Console.ReadKey(); 23 24 } 25 } 26 }