算法競賽入門經典第2版 第1章
學習目標:
熟悉C語言程序的編譯和運行
學會編程計算並輸出常見的算術表達式的結果
掌握整數和浮點數的含義和輸出方法、聲明方法、讀入方法
掌握數學函數的使用方法
初步了解變量的含義
掌握變量交換的三變量法
理解算法競賽中的程序三部曲:輸入、計算、輸出
記住算法競賽的目標及其對程序的要求
1.2 變量及其輸入
1.如果一定要把浮點數值存放在一個int型變量中,將會丟失部分信息——不推薦這樣做。
例1-1 圓柱體的表面積
#include <stdio.h> int main() { const double pi = acos(-1.0); double r,h,s1,s2; scanf("%lf %lf",&r,&h); s1 = 2*pi*r*r; s2 = 2*pi*r*h; printf("Area = %.3f\n",s1+s2); return 0; }
(1).不要讓程序“按任意鍵退出”(例如,調用system(“pause”),或者添加一個多余的getchar()),因為不會有人來“按任意鍵”的。
(2).在算法競賽中,不要使用頭文件conio.h,不要使用getch(),getche(),gotoxy()和clrscr()函數。
1.3 順序結構程序設計
例1-2 三位數反轉
#include <stdio.h> int main() { int a,a1,a2,a3,b; scanf("%d",&a); a1 = a/100; a2 = (a-a1*100)/10; a3 = a%10; b= a3*100+a2*10+a1; printf("%d\n",b); //考慮最後一位為0時的輸出,%d或%03d return 0; }
(1).註意數的最後一位為0時如何取值。
例1-3 交換變量
#include <stdio.h> int main() { /* 三變量法 int a,b,temp; scanf("%d %d",&a,&b); temp = a; a = b; b = temp; printf("%d %d",a,b);*/ //最佳的方法: int a,b; scanf("5d %d",&a,&b); printf("%d %d",b,a); return 0; }
(1).算法競賽是在比誰能更好地解決問題,而不是在比誰寫的程序看上去更高級。
1.4 分支結構程序設計
例1-4 雞兔同籠
#include <stdio.h> int main() { int m,n,j,t; scanf("%d %d",&n,&m); t = (m-2*n)/2; j = n-t; if(m%2 == 1 || j<0 || t<0) printf("No answer"); else printf("%d %d\n",j,t); return 0; }
(1).和其他語言不同的是,在C語言中單個整數也可以表示真假,其中0為假,其他值為真。
(2).短路運算
例1-5 三整數排序
#include <stdio.h> int main() { int a,b,c,t; 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("%d %d %d",a,b,c); return 0; }
算法競賽入門經典第2版 第1章