交换两个变量的值,不使用第三个变量

来源:互联网 发布:三菱plc编程入门 pdf 编辑:程序博客网 时间:2024/06/06 05:07

如何不借助第三个变量,来交换两个变量的值?

一种解决办法是根据两个变量在数轴上的距离来交换数值。


a=b-a; 此时a为a和b的距离差。

b=b-a;b的距离减去差值则为a,此时b的值为原来的a;

a=b+a;相当于原来a的值加上a和b的距离差,此时a的值为原来的b;


// aa.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <stdlib.h>#include <stdio.h>#include <string.h>int main(int argc, char* argv[]){  int a=5;  int b=12; a=b-a;b=b-a;a=b+a;printf("%d",a);printf("\n");printf("%d",b);    printf("\n"); return 0; }


阅读全文
0 0
原创粉丝点击