C#复习_不使用第三个变量交换两个int类型变量的值

来源:互联网 发布:网络数据库技术 编辑:程序博客网 时间:2024/06/05 15:47
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;        }    }}

0 0
原创粉丝点击