在 C# 中交换两个数字
要交换两个数字,请按照以下逻辑进行操作。
设置两个变量进行交换 -
val1 = 100; val2 = 200;
现在执行以下交换操作 -
val1 = val1 + val2; val2 = val1 - val2; val1 = val1 - val2;
以下是代码 -
示例
using System; namespace Demo { class Program { static void Main(string[] args) { int val1,val2; val1 = 100; val2 = 200; 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(); } } }
广告