《第 03 讲:循环结构》
1. (*)有 10 亿元钱每天花一半,可以花多少天?
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { int money = 100000000; int i = 0; while (money != 0) { money /= 2; printf("%2d %d\n", i + 1, money); i++; } 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: |
本文出自 “帝国金菜园子” 博客,谢绝转载!
原文地址:http://diguojin.blog.51cto.com/5034509/1622346