3種方法交換兩個整數(不建立臨時變數)+輸出一組資料最大值+簡單排序+最大公約數
阿新 • • 發佈:2018-11-28
交換兩個整數:
第一種:
int a = 6;
int b = 8;
int t = 0;
t = a;
a = b;
b = t;
printf("a = %d b = %d\n", a, b);
後兩種不建立臨時變數
第二種:
int a = 6;
int b = 8;
a = a + b;
b = a - b;//b = 6
a = a - b;//a = 8;
printf("a = %d b = %d\n", a, b);
第三種:
int a = 6; int b = 8; a = a ^ b; b = a ^ b;//b = 6 a = a ^ b;//a = 8 printf("a = %d b = %d\n", a, b);
輸入一組資料,並輸出這組資料的最大值:
#include<stdio.h> /* 輸入一組資料,輸出最大值 */ int max(int a[]) { //int k = 0; //for (int i = 0;i<9;i++){ // if (a[k]<a[i+1]) { // k = i + 1; // } //} //return a[k]; int max = 0; for (int i = 0; i < 10;i++) { if (max < a[i]) { max = a[i]; } } return max; } int main() { int a[10]; printf("Please input 10 numbers in the screen:\n"); for (int i = 0; i < sizeof(a)/4; i++) { scanf("%d", &a[i]); } printf("The max number of these datas is %d\n", max(a)); return 0; }
輸入3個數,按從大到小的順序輸出:
#include<stdio.h> /* 輸入3個數,按從大到小的順序輸出 */ int main() { int a = 0, b = 0, c = 0; int t = 0; printf("Please input 3 numbers (every number is separated with space) :\n"); scanf("%d %d %d", &a, &b, &c); if (a < b) { t = a; a = b; b = t; } if (a < c) { t = a; a = c; c = t; } if (b < c) { t = b; b = c; c = t; } printf("The 3 numbers from big to small: %d %d %d\n", a, b, c); return 0; }
輸入兩個數,求這兩個數的最大公約數:
#include<stdio.h>
/*
求兩個數的最大公約數
*/
int main() {
int a = 0, b = 0;
int judge = 0;
printf("Please input 2 numbers:");
scanf("%d %d", &a, &b);
while ((judge = a % b) != 0) {
a = b;
b = judge;
}
printf("The max common divisor is : %d\n", b);
return 0;
}