1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace practice1 8 { 9 class Program 10 { 11 --------------------------------------------------------------------------------------- 12 #使用一般方式,交换两个变量的值 13 static void Main(string[] args) 14 { 15 #region 声明两个变量:int n1=10, n2=20 ; 要求将两个变量交换,最后输出n1=20,n2=10, 扩展(*):不使用第三个变量如何交换? 16 int n1 = 10, n2 = 20; 17 18 #常规的交换数据方式 19 int temp=n1; 20 n1= n2; 21 n2= temp; 22 23 #数学技术来交换数据方式 24 n1 = n1 + n2; 25 n2 = n1 - n2; 26 n1 = n1 - n2; 27 28 Console.WriteLine("n1= "+n1); 29 Console.WriteLine("n2= "+n2); 30 Console.ReadKey(); 31 32 #endregion 33 } 34 ------------------------------------------------------------------------------------ 35 #使用封装,来处理两个变量的值交换 36 static void Main(string[] args) 37 { 38 #region 用方法来实现:封装一个方法来做,方法有两个参数分别为num1,num2,将num1与num2交换。提示:方法有两个参数n1、n2,在方法中将n1与n2进行交换,使用ref(*) 39 40 int n1 = 10, n2 = 20; 41 42 Swap(ref n1, ref n2); 43 44 Console.WriteLine("n1= "+n1); 45 Console.WriteLine("n2= "+n2); 46 Console.ReadKey(); 47 48 #endregion 49 } 50 51 private static void Swap(ref int n1, ref int n2) 52 { 53 //throw new NotImplementedException(); 54 int tmp = n1; 55 n1 = n2; 56 n2 = tmp; 57 } 58 -------------------------------------------------------------------------------------- 59 } 60 } 61
时间: 2024-10-13 19:54:54