使用臨時(shí)變量
以下實(shí)例演示了交換兩個(gè)浮點(diǎn)數(shù)得值。
實(shí)例
#include <stdio.h>
int main()
{
double firstNumber, secondNumber, temporaryVariable;
printf("輸入第壹個(gè)數(shù)字: ");
scanf("%lf", &firstNumber);
printf("輸入第二個(gè)數(shù)字: ");
scanf("%lf",&secondNumber);
// 將第壹個(gè)數(shù)得值賦值給 temporaryVariable
temporaryVariable = firstNumber;
// 第二個(gè)數(shù)得值賦值給 firstNumber
firstNumber = secondNumber;
// 將 temporaryVariable 賦值給 secondNumber
secondNumber = temporaryVariable;
printf("\n交換后, firstNumber = %.2lf\n", firstNumber);
printf("交換后, secondNumber = %.2lf", secondNumber);
return 0;
}
運(yùn)行結(jié)果:
輸入第壹個(gè)數(shù)字: 1輸入第二個(gè)數(shù)字: 2交換后, firstNumber = 2.00交換后, secondNumber = 1.00
不使用臨時(shí)變量
不使用臨時(shí)變量交換兩個(gè)整數(shù)得值:
實(shí)例
#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) 此時(shí) a 得變量為兩數(shù)之和,b 未改變
b = a - b; // ( 110 - 99 = 11)
a = a - b; // ( 110 - 11 = 99)
printf("交換后 - \n a = %d, b = %d \n", a, b);
}
運(yùn)行結(jié)果:
交換之前 - a = 11, b = 99 交換后 - a = 99, b = 11