题目
1
声明两个变量:int n1 = 10,n2= 20,要求将两个变量叫唤,最后输出n1为20,n2为10.
(扩展*: 不使用第三个变量如何交换)
解决方案
基本方法
private static void BasicMethod()
{
int n1 = 10;
int n2 = 20;Console.WriteLine("n1={0}", n1);
Console.WriteLine("n2={0}", n2);int tem = n1;
Console.WriteLine("tem = n1, 此时tem = {0}", n1);
n1 = n2;
Console.WriteLine("n1 = n2, 此时 n1 = {0}", n2);
n2 = tem;
Console.WriteLine("n2 = tem, 此时 n2 = {0}", n2);Console.WriteLine("经过交换之后 n1 = {0},n2= {1}", n1, n2);
Console.WriteLine("点击任意键结束程序...");
Console.ReadLine();
}
扩展方法
private static void ExpandMethod()
{
int n1 = 10;
int n2 = 20;Console.WriteLine("n1={0}", n1);
Console.WriteLine("n2={0}", n2);n1 = n1 + n2;
Console.WriteLine("n1 = n1 + n2;此时n1={0}", n1);n2 = n1 - n2;
Console.WriteLine("n2 = n1 - n2;此时n1={0},n2={1}", n1, n2);
n1 = n1 - n2;
Console.WriteLine("n1 = n1 - n2;此时n1={0},n2={1}", n1, n2);Console.WriteLine("经过交换之后 n1 = {0},n2= {1}", n1, n2);
Console.WriteLine("点击任意键结束程序...");
Console.ReadLine();
}
基础练习 - 数值交换