首页 > 其他分享 >用C语言实现两个值交换的四种方法

用C语言实现两个值交换的四种方法

时间:2022-10-16 16:08:08浏览次数:52  
标签:return int d% 交换 C语言 瓶子 printf include 四种

一.题中已给两个值的数值

二.随意输出两个整数(变量)的数值

为避免麻烦,我在这里统一用变量(就是第二种)来敲一遍,希望可以给各位解决些麻烦,仅供参考,希望指正。另外,下面的代码我用了不懂颜色进行了标注,方便大家理解,发现相同之处和不同之处。

1.引入第三方(暴力求解)

为生动理解,我举下例子:

你有三个瓶子,1号瓶子:可乐   2号瓶子:雪碧   3号:空瓶

现在想要把可乐倒进2号瓶子,把雪碧倒进1号瓶子,此时3号瓶子就是辅助的,所以一般的顺序为:

将可乐倒进3号瓶子—>将雪碧倒进1号瓶子—>再将3号瓶子中装的可乐倒进2号瓶子。

因此代码可以借鉴

#include<string.h>

#include <stdio.h>

int main()

{

int a,b,c;

scanf("%d%d",&a,&b);

printf("变化前:a=%d  b=%d\n",a,b);

c=a;

a=b;

b=c;

printf("变化后:a=%d  b=%d\n",a,b);

return  0;

}

2.第二种    加减运算, 不创建临时变量

#include<stdio.h>

#include<string.h>

int main()

{

int a,b;

scanf("%d%d",&a,&b);

printf("变化前:a=%d  b=%d\n",a,b);

a=a+b;

b=a-b;

a=a-b;

printf("变化后:a=%d  b=%d\n",a,b);

return  0;

}

3.第三种   异或运算, 不创建临时变量

#include<stdio.h>

#include<string.h>

int main()

{

int a,b;

scanf("%d%d",&a,&b);

printf("变化前:a=%d  b=%d\n",a,b);

a=a^b;

b=a^b;

a=a^b;

printf("变化后:a=%d  b=%d\n",a,b);

return  0;

}

4.第四种  位运算 (2进制)注:不适用于大数字

#include<stdio.h>

#include<string.h>

int main()

{

int a,b;

scanf("%d%d",&a,&b);

printf("变化前:a=%d  b=%d\n",a,b);

a=a<<8;

a=a+b;

b=a>>8;

a=a&0xff;

printf("变化后:a=%d  b=%d\n",a,b);

return  0;

}

总结  :除第一个外 ,其他均未引入其他的变量。

          采用引入第三方变量的方法,代码可读性高,执行效率更快。但是 第三方还是第三方,多了就是多了,就会导致  “溢出”的问题。

         对于异或运算,它的可读性较差,执行的效率不高。

总之:对于这种题目相对简单,大家应注意灵活运用。

       ​










标签:return,int,d%,交换,C语言,瓶子,printf,include,四种
From: https://blog.51cto.com/u_15806064/5760332

相关文章