短路属性、scanf 的秘密和队列
1 2 3 4 | 条件表达式
逻辑运算符的短路属性
scanf 的秘密
队列 FIFO的基本知识 |
1 2 3 4 5 6 7 | 1006 Problem A 求三个数的最大值 1089 Problem B 偶数(odd) 1070 Problem C 求组合数 1072 Problem D 求n个整数之中的偶数之和 1079 Problem F 求素数之和 1060 Problem G 最大公约数和最小公倍数 1158 Problem H 卡片游戏 |
1 2 3 4 5 6 7 8 9 10 11 12 | #include <stdio.h> int main(int argc, char *argv[]) { int a, b, c, max; scanf("%d%d%d", &a, &b, &c); max = a; if (b>max) max = b; if (c>max) max = c; printf("%d\n", max); return 0; } |
你会用条件表达式吗?
1 2 3 4 5 6 7 8 9 10 11 12 | #include <stdio.h> int main(int argc, char *argv[]) { int a, b, c, max; scanf("%d%d%d", &a, &b, &c); max = a; max = (b>max) ? b : max; max = (c>max) ? c : max; printf("%d\n", max); return 0; } |
还有更简单的写法吗?答案是肯定的。
1 2 3 4 5 6 7 8 9 10 11 12 | #include <stdio.h> int main(int argc, char *argv[]) { int a, b, c, max; scanf("%d%d%d", &a, &b, &c); max = a; (b>max) && (max=b); (c>max) && (max=c); printf("%d\n", max); return 0; } |
《C程序设计语言 第2版新版》第32页:逻辑运算符的特殊属性
还有其他写法?
1 2 3 4 5 6 7 8 9 10 11 12 | #include <stdio.h> int main(int argc, char *argv[]) { int a, b, c, max; scanf("%d%d%d", &a, &b, &c); max = a; (max>b) || (max=b); (max>c) || (max=c); printf("%d\n", max); return 0; } |
1089 Problem B 偶数(odd)
1 2 3 4 5 6 7 8 9 | #include <stdio.h> int main(int argc, char *argv[]) { int n; while (成功读取一个数) { } return 0; } |
填空
1 2 3 4 5 6 7 8 9 10 | #include <stdio.h> int main(int argc, char *argv[]) { int n; while (scanf("%d", &n)==1) { (n%2==0) && printf("yes\n"); (n%2==1) && printf("no\n"); } return 0; } |
1070 Problem C 求组合数
写好计算阶乘的函数,问题就变得非常简单了!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <stdio.h> int jc(int n) { int i, p=1; for(i=2; i<=n; i++) p *= i; return p; } int main(int argc, char *argv[]) { int m, n; scanf("%d%d", &m, &n); printf("%d\n", jc(m)/(jc(m-n)*jc(n))); return 0; } |
1079 Problem F 求素数之和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <stdio.h> #include <math.h> int is_prime(int n) { int i, t; if (n==1) return 0; t = sqrt(n); for (i=2; i<=t; i++) { if (n%i == 0) return 0; } return 1; } int main(int argc, char *argv[]) { int m, n, i, sum=0; scanf("%d%d", &m, &n); for (i=m; i<=n; i++) is_prime(i) && (sum += i); printf("%d\n", sum); return 0; } |
1158 Problem H 卡片游戏
请搜索“卡片游戏”