如何在C#中不使用临时变量交换两个数字
要交换两个数字,使用第三个变量并执行算术运算符而不使用临时变量。
设置两个变量进行交换 -
val1 = 5; val2 = 10;
现在执行以下操作以进行交换 -
val1 = val1 + val2; val2 = val1 - val2; val1 = val1 - val2;
示例
using System; namespace Demo { class Program { static void Main(string[] args) { int val1,val2; val1 = 5; val2 = 10; Console.WriteLine("Values before swap..."); Console.WriteLine(val1.ToString()); Console.WriteLine(val2.ToString()); val1 = val1 + val2; val2 = val1 - val2; val1 = val1 - val2; Console.WriteLine("Values after swap..."); Console.WriteLine(val1.ToString()); Console.WriteLine(val2.ToString()); Console.ReadLine(); } } }
广告