Skip to content
On this page

变量的值交换

交换 2 个变量的值,就如同交换两只杯子中的饮料:一杯满满的牛奶和一杯满满的咖啡,怎样才能互换呢?

img

变量的交换也如此。两个变量的交换也需要一只“空杯子”,就是中间变量

csharp
string a = "振刚"; // 第一个变量
string b = "文峰"; // 第二个变量
string temp; // 中间变量
// 第一步:将变量 a 赋值给中间变量
temp = a; // 如同牛奶倒入空杯
// 第二步:将变量 b 赋值给变量 a
a = b; // 如同咖啡倒入牛奶杯
// 第三步:将中间变量赋值给变量 b
b = temp; // 如同空杯中的牛奶倒入咖啡杯
// 此时交换完成,变量 a 存储了“文峰”,b 存储了“振刚”

这种 解决实际问题的步骤就叫做“算法”交换 就是最常用的一种算法。

csharp
using System;
using System.Collections.Generic;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        { 
            string boy = "秀丽"; // 男孩名字
            string girl = "伟强"; // 女孩名字
            string temp; // 中间变量
            temp = boy; // 把男孩的名字赋值给 temp
            boy = girl; // 把女孩的名字赋值给男孩
            girl = temp; // 把 temp 中的名字赋值给女孩
            Console.WriteLine("男孩叫" + boy + " 女孩叫" + girl);
        }
    }
}
csharp
using System;
using System.Collections.Generic;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        { 
            string today; // 今天的午饭
            string tomorrow; // 明天的午饭
            today = "鱼香肉丝";
            tomorrow = "小鸡炖蘑菇";
            // 请在这里补充代码,实现变量 today 和 tomorrow 的交换

            string temp = today;
            today = tomorrow;
            tomorrow = temp;

            // 打印
            Console.WriteLine("我今天吃{0},明天吃{1}。", today, tomorrow);
        }
    }
}