声明两个变量:int n1 = 10, n2 = 20;要求将两个变量交换,最后输出n1为20,n2为10。
在主函数中实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{ int n1=10,n2=20;
Console.WriteLine("交换前的n1={0},n2={1}",n1,n2);
int c;
c = n1;
n1 = n2;
n2 = c;;
Console.WriteLine("交换后的n1={0},n2={1}",n1,n2);
Console.ReadKey();
}
}
}
不使用第三个变量进行交换两个数的值
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{ int n1=10,n2=20;
Console.WriteLine("交换前的n1={0},n2={1}",n1,n2);
n1 = n1 ^ n2;
n2 = n2 ^ n1;
n1 =n1 ^n2;
Console.WriteLine("交换后的n1={0},n2={1}",n1,n2);
Console.ReadKey();
}
}
}
实现结果