您的位置:首页 > 编程语言 > C#

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

2015-02-03 17:13 405 查看
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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: