C#複習_不使用第三個變數交換兩個int型別變數的值
阿新 • • 發佈:2019-01-03
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _05不使用temp變數int型別資料交換 { class Program { static void Main(string[] args) { Console.WriteLine("請輸入n1"); int n1 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("請輸入n2"); int n2 = Convert.ToInt32(Console.ReadLine()); ExchangeTwoInt(ref n1, ref n2); Console.WriteLine("n1={0}",n1); Console.WriteLine("n2={0}",n2); Console.ReadKey(); } //ref是把值傳遞轉換為引用傳遞,指向棧上的同一塊地址 private static void ExchangeTwoInt(ref int n1, ref int n2) { n1 = n1 - n2; n2 = n1 + n2;//此時n2中存放的是n1的值 //n1中要放n2的值 n1 = n2 - n1; } } }