C 语言实例 - 交换两个数的值

C 语言教程 · 2019-02-20 15:57:20

使用临时变量

以下实例演示了交换两个浮点数的值。

实例

#include <stdio.h> int main() { double firstNumber, secondNumber, temporaryVariable; printf("输入第一个数字: "); scanf("%lf", &firstNumber); printf("输入第二个数字: "); scanf("%lf",&secondNumber); // 将第一个数的值赋值给 temporaryVariable temporaryVariable = firstNumber; // 第二个数的值赋值给 firstNumber firstNumber = secondNumber; // 将 temporaryVariable 赋值给 secondNumber secondNumber = temporaryVariable; printf("\n交换后, firstNumber = %.2lf\n", firstNumber); printf("交换后, secondNumber = %.2lf", secondNumber); return 0; }

运行结果:

输入第一个数字: 1
输入第二个数字: 2

交换后, firstNumber = 2.00
交换后, secondNumber = 1.00

不使用临时变量

不使用临时变量交换两个整数的值:

实例

#include <stdio.h> int main() { int a, b; a = 11; b = 99; printf("交换之前 - \n a = %d, b = %d \n\n", a, b); a = a + b; // ( 11 + 99 = 110) 此时 a 的变量为两数之和,b 未改变 b = a - b; // ( 110 - 99 = 11) a = a - b; // ( 110 - 11 = 99) printf("交换后 - \n a = %d, b = %d \n", a, b); }

运行结果:

交换之前 - 
 a = 11, b = 99 

交换后 - 
 a = 99, b = 11 

点击查看所有 C 语言教程 文章: https://www.codercto.com/courses/l/17.html

查看所有标签

Looking For a Challenge

Looking For a Challenge

the University of Warsaw / the University of Warsaw / 2012-11 / 0

LOOKING FOR PROGRAMMING CHALLENGES? Then this book is for you! Whether it's the feeling of great satisfaction from solving a complex problem set, or the frustration of being unable to solve a task,......一起来看看 《Looking For a Challenge》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

html转js在线工具
html转js在线工具

html转js在线工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具