A016:三數排序
三數排序
輸入三個正整數a、b、c,將a、b、c從小排到大。
鍵詞
<:鍵詞 至少=0 最多=1 擁有=9999>include<:>
<:鍵詞 至少=0 最多=0 擁有=9999>[<:>
<:鍵詞 至少=0 最多=0 擁有=9999>]<:>
Input
192 706 184
Output
184 192 706
Notes:
1.兩數字比較大小,數字小的在前面,數字大的在後面
利用邏輯運算子,若數字小的在後面,則將兩個數字互換
void swap(int *a,int *b){
if(*a>*b){
*a^=*b;
*b^=*a;
*a^=*b;
}
}
2. 先將數字1數字2比較,再將數字2與數字3比較,最後數字1與數字2再比一次,確保最小的數字在第一個
swap(&num1,&num2);
swap(&num2,&num3);
swap(&num1,&num2);
Code:
#include <stdio.h>
void swap(int *a,int *b){
if(*a>*b){
*a^=*b;
*b^=*a;
*a^=*b;
}
}
int main(void){
int num1,num2,num3;
scanf("%d %d %d",&num1,&num2,&num3);
swap(&num1,&num2);
swap(&num2,&num3);
swap(&num1,&num2);
printf("%d %d %d",num1,num2,num3);
return 0;
}
交換整數可以寫成 *a ^= *b ^= *a ^= *b
回覆刪除