非學無以廣才截粗,非志無以成學
1-1 整數(shù)值用%d輸出秉版,實數(shù)用%f輸出
1-2 scanf中的占位符和變量的數(shù)據類型一一對應,且每個變量前需要加&符號
1-3 盡量用const關鍵字聲明常數(shù)宽菜,const double pi = acos(-1.0);
1-4 C99標準中double的輸入采用%lf盼理,輸出必須采用%f
1-5 算法競賽是在比誰能更好地解決問題辅愿,而不是在比誰寫的程序看上去更高級
1-6 int型整數(shù)和double型浮點數(shù)的最大最小值
#include <iostream>
#include <limits.h>
#include <float.h>
using namespace std;
int main()
{
cout<<"最大int型整數(shù)"<<INT_MAX<<endl;
cout<<"最小int型整數(shù)"<<INT_MIN<<endl;
cout<<"最大double型實數(shù)"<<DBL_MAX<<endl;
cout<<"最小double型實數(shù)"<<DBL_MIN<<endl;
return 0;
}
2-1 建議盡量縮短變量的定義范圍智亮。例如在for循環(huán)的初始化部分定義循環(huán)變量
2-2 在目前流行的競賽平臺上,int都是32位整數(shù)点待,范圍為-2^31 ~ 2^31-1
2-3 乘法時整數(shù)溢出阔蛉,則使用long long , 范圍為-2^63 ~ 2^63-1
2-4 long long 在Linux下的輸入輸出格式符為%lld,但在Windows平臺中有時為%I64d.為保險起見癞埠,可以用C++流馍忽,或者編寫自定義輸入輸出函數(shù)。
2-5 使用計時函數(shù)返回程序目前為止運行的時間燕差。引入<time.h>
頭文件,輸出為printf("Time used = %.2f\n", (double)clock() / CLOCKS_PER_SEC);
2-6 scanf函數(shù)返回的是成功輸入的變量個數(shù)
2-7 輸入輸出數(shù)據保存在文件中
- 使用重定向方式
#define LOCAL
#include<stdio.h>
int main()
{
#ifdef LOCAL
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif
int x, s = 0, n = 0;
while(scanf("%d", &x) == 1)
{
s+=x;
n++;
}
printf("%.3f\n",(double)s/n);
return 0;
}
如果比賽要求使用標準輸入輸出坝冕,只需在提交之前刪除#define LOCAL
即可徒探。
- 如果比賽要求用文件輸入輸出,但禁止使用重定向方式喂窟,應使用fopen和fscanf/fprintf進行輸入輸出测暗。
#include<stdio.h>
int main()
{
FILE *fin, *fout;
fin = fopen("data.in", "rb");
fout = fopen("data.out", "wb");
int x, s = 0, n = 0;
while(fscanf(fin, "%d", &x) == 1)
{
s+=x;
n++;
}
fprintf(fout, "%.3f\n", (double)s/n);
fclose(fin);
fclose(fout);
return 0;
}
如果想把它改成標準輸入輸出,只需賦值fin = stdin; fout = stdout;
即可磨澡,不用調用fopen和fclose.
2-8 在輸入為多組數(shù)據的題目中碗啄,一個常見的錯誤就是:在計算完一組數(shù)據后某些變量沒有重置,影響到下組數(shù)據的求解稳摄。
2-9 要計算只包含加法稚字,減法和乘法的整數(shù)表達式除以正整數(shù)n的余數(shù),可以在每步計算之后對n取余,結果不變胆描。
2-10 輸出保留到小數(shù)點后c位printf("%.*f\n", c, s*1.0/n);