C语言实验——交换两个整数的值(顺序结构)

本文介绍了在C语言中交换两个变量值的两种常见方法:一种是使用第三个临时变量,另一种是通过数学运算实现,无需额外变量。文章提供了详细的代码示例及运行结果,适合初学者理解变量交换的基本原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description
交换两个变量的值,由终端输入两个整数给变量x、y,然后交换x和y的值后,输出x和y。
Input

键盘输入两个整数变量x和y;

Output

在交换x、y的值后将x和y输出!

Sample Input

4 6

Sample Output

6 4

Hint
Source
**方法一:**借助第三变量

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x,y,z;
    scanf("%d %d",&x,&y);
    z=x;     //将a的值暂时存在c中
    x=y;
    y=z;
    printf ("%d %d\n",x,y);
    return 0;
}

运行结果:
4 6
6 4

Process returned 0 (0x0)   execution time : 03.125 s
Press any key to continue.

**方法二:**不借助第三变量

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x,y;
    scanf("%d %d",&x,&y);
    x = x + y;     
    y = x - y;      //y等于(x + y)- y;
    x = x - y;      //x等于(x+y)- [(x+y)-y];
    printf ("%d %d\n",x,y);
    return 0;
}

运行结果:
4 6
6 4

Process returned 0 (0x0)   execution time : 04.687 s
Press any key to continue.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

碧羽o(* ̄▽ ̄*)ブ回雪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值