2.1 for 循環(huán)
2.2 while 循環(huán)和 do-while 循環(huán)
2.3 循環(huán)的代價
-
windows 下的的管道輸入
echon|程序名n 是要輸入的值 -
Linux 下的管道輸入
echon|./程序名
2.4 算法競賽中的輸入輸出框架
-
結(jié)束輸入的方式:
- Windows: Enter, Ctrl+Z, Enter
- Linux: Ctrl+D
-
文件比較命令:
- Windows: fc
- Linux: diff
-
輸入輸出重定向:
在 main 函數(shù)的入口加入下面兩條語句(文件名不允許使用絕對或相對路徑)
freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); -
本機(jī)使用文件重定向,上交時刪除的方法:
#define LOCAL //提交時刪除這一行 #include <stdio.h> int main() { #ifdef LOCAL //本機(jī)執(zhí)行的語句,如文件重定向 #endif //...其他語句 }也可以在編譯選項中定義 LOCAL 符號而不是在代碼中,這樣更不容易出錯。
方法是在編譯選項中加入
-DLOCAL -
使用文件輸入輸出,但不使用重定向的方式:
int main() { FILE *fin, *fout; fin = fopen("data.in", "rb"); //rb 是二進(jìn)制讀方式打開文件 fout = fopen("data.out", "wb"); //wb 是二進(jìn)制寫方式打開文件 //如果想改成標(biāo)準(zhǔn)輸入輸出,令 fin = stdin, fout = stdout, 且不寫 fclose 語句即可 int x; while(fscanf(fin, "%d", &x) == 1) { //輸入語句使用 fscanf,第一個參數(shù)是輸入文件,后面的參數(shù)和 scanf 相同 //... } fprintf(fout, "%d", x); fclose(fin); fclose(fout); //最后應(yīng)當(dāng)關(guān)閉輸入輸出文件 return 0; } -
魯棒性(robustness)
可以理解成程序的健壯性或穩(wěn)定性
編譯選項
-Wall可以打出編譯警告
2.5 注解與習(xí)題(python 實現(xiàn))
-
水仙花數(shù)(三位數(shù))
for i in range(100, 1000): a = int(i / 100) b = int(i % 100 / 10) c = int(i % 10) if a*a*a + b*b*b + c*c*c == i: print(i) -
韓信點兵:士兵以三人一排,五人一排,七人一排的隊形排列
輸入中包含多組數(shù)據(jù),每組數(shù)據(jù)包含三個非負(fù)整數(shù) a, b, c,表示每一種隊形排尾的人數(shù)(a<3, b<5, c<7),輸出總?cè)藬?shù)的最小值或報告無解。已知總?cè)藬?shù)不小于10,不超過100
import sys for line in sys.stdin: # 作用等同于 while(cin) # split() 函數(shù)默認(rèn)分隔符是空格 a, b, c = line.split()[:3] a = int(a) b = int(b) c = int(c) for x in range(10, 101): if int(x % 3) == a and int(x % 5) == b and int(x % 7) == c: print(x) break elif x == 100: print('no answer') -
倒三角形
n = int(input()) for i in range(n): for blank in range(i): print(' ', end="") for sharp in range(2*(n-i)-1, 0, -1): print('#', end="") if i != n-1: print("") -
子序列的和
import sys for line in sys.stdin: n, m = line.split()[:2] n = int(n) m = int(m) if n == 0 and m == 0: break else: result = 0.0 while n <= m: result += 1 / (n * n) n += 1 print("%.5f" % result) -
分?jǐn)?shù)化小數(shù):輸出 a/b 保留 c 位小數(shù)的結(jié)果
import sys for line in sys.stdin: a, b, c = line.split()[:3] a = int(a) b = int(b) c = int(c) if not a and not b and not c: break else: formatStr = "%%.%df" % c print(formatStr % (a/b)) -
排列:使用1-9組成 abc, def, ghi 三個數(shù)并輸出,要求三個數(shù)的比值為1:2:3,每個數(shù)字僅使用一次
hash = [0] * 10
hash[0] = 1
def check(x):
a = int(x / 100)
b = int(x / 10 % 10)
c = int(x % 10)
if a != b and b != c and a != c and not hash[a] and not hash[b] and not hash[c]:
hash[a] = hash[b] = hash[c] = 1
return True
else:
return False
for x in range(123, 330):
hash = [0] * 10
hash[0] = 1
if check(x) and check(x+x) and check(x+x+x):
print(x, x+x, x+x+x)
```