《第 03 講:循環結構》
1. (*)有 10 億元錢天天花一半,能夠花多少天?編程
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) {ide int money = 100000000;spa int i = 0;code while (money != 0) {orm money /= 2;ci printf("%2d %d\n", i + 1, money);get i++;input }it printf("第%d天能夠花光\n",i); return 0; } 1 50000000 2 25000000 3 12500000 4 6250000 5 3125000 6 1562500 7 781250 8 390625 9 195312 10 97656 11 48828 12 24414 13 12207 14 6103 15 3051 16 1525 17 762 18 381 19 190 20 95 21 47 22 23 23 11 24 5 25 2 26 1 27 0 第27天能夠花光 Program ended with exit code: 0 |
2. (**)隨機產生 20 個[10 , 100]的正整數,輸出這些數以及他們中的最大數
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { int randint = 0, max = 0, i = 0; printf("輸入任意鍵打印20個[10, 100]的正整數,ctrl+d退出:"); while (getchar() != EOF) { for (i = 0; i < 20; i++) { randint = arc4random() % 91 + 10; printf("%d ", randint); max = max > randint ? max : randint; } printf("\nmax is %d\n", max); printf("輸入任意鍵打印20個[10, 100]的正整數,ctrl+d退出:"); }
return 0; } 結果: 輸入任意鍵打印20個[10, 100]的正整數,ctrl+d退出: 37 74 26 81 83 73 25 53 31 38 64 21 45 97 13 33 13 59 48 64 max is 97 輸入任意鍵打印20個[10, 100]的正整數,ctrl+d退出: |
3. (**)編程將全部「水仙花數」打印出來,並打印其總個數。 「水仙花數」
是一個 各個位立方之和等於該整數的三位數。
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { int i = 0, j = 0, k = 0;
for (i = 1; i < 10; i ++) { for (j = 0; j < 10; j++) { for (k = 0; k < 10; k++) { if( (i*100+j*10+k) == (i*i*i + j*j*j + k*k*k) ){ printf("%d%d%d ",i,j,k); } } } } return 0; } 結果: 153 370 371 407 Program ended with exit code: 0 |
4.(**)已知 abc+cba = 1333,其中 a,b,c 均爲一位數,編程求出知足條件的 a,b,c 全部組合
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { int i = 0, j = 0, k = 0;
for (i = 1; i < 10; i++) { for (j = 0; j < 10; j++) { for (k = 0; k < 10; k++) { if(i*100 + j*10 + k + k*100 + j*10 + i == 1333) { printf("%d%d%d ", i, j, k); } } } } putchar('\n'); return 0; } 結果: 419 518 617 716 815 914 Program ended with exit code: 0 |
5. (***)輸入兩個數,求最大公約數和最小公倍數。(用兩種方法:展轉相除法和普通方法)
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { int a = 0, b = 0, c = 0, t = 0; printf("Please input two int:"); while (scanf("%d%d", &a, &b) != EOF) { if(a < b){ a = a ^ b; b = a ^ b; a = a ^ b; } c = a * b; while(b != 0 ){ t = a % b; a = b; b = t; } printf("The GCD is %d\n", a); printf("The LCM is %d\n", c / a); printf("Continue input two int:"); } return 0; } 結果 Please input two int:12 36 The GCD is 12 The LCM is 36 Continue input two int: |