C# 变量交换

C#  变量交换

 变量交换的方法:

1.借助第三个变量:

 1     class Program

 2     {

 3         static void Main(string[] args)

 4         {

 5             Exchage(10,5);

 6         }

 7         /// <summary>

 8         /// 交换变量,借助第三个变量

 9         /// </summary>

10         /// <param name="num1"></param>

11         /// <param name="num2"></param>

12         private static void Exchage(int num1, int num2)

13         {

14             //交换前

15             Console.WriteLine("num1的值:{0};num2的值:{1}", num1, num2);

16             int temp = num1;

17             num1 = num2;

18             num2 = temp;

19             //交换后

20             Console.WriteLine("num1的值:{0};num2的值:{1}", num1, num2);

21             Console.ReadKey();

22 

23         }

24      }
View Code

 

2.累加法:

 1  class Program

 2     {

 3         static void Main(string[] args)

 4         {

 5             Exchage(10,5);

 6         }

 7             /// <summary>

 8         /// 交换变量,使用累加法

 9         /// </summary>

10         /// <param name="num1"></param>

11         /// <param name="num2"></param>

12         private static void Exchage(int num1,int num2)

13         {

14             //交换前

15              Console.WriteLine("num1的值:{0};num2的值:{1}", num1, num2);

16             num1 = num1 + num2;

17             num2 = num1 - num2;

18             num1 = num1 - num2;

19             Console.WriteLine("num1的值:{0};num2的值:{1}", num1, num2);

20             Console.ReadKey();

21 

22         }

23     }
View Code

 

你可能感兴趣的:(C#)