精華區beta b885060xx 關於我們 聯絡資訊
* 程式撰寫: 本程式使用 joe 編輯, 用 gcc -o hw2 hw2.c 編譯 繳交前用 Turbo C++ 3.0 compile 為 hw2.exe * 程式作法 程式碼很簡單, 分為三段, 分別是 1. 讀入使用者的代碼 2. 讀入時間, 在讀入時間的同時計算應付的錢 3. 印出該使用者應付的費用 我利用 structure 的 array, 將各種費率及基本費儲存在一起, 好處是若是 費率變動易於將來修改另一方面, 由於使用 array, 使得三種計價方式的計算 可以用相同的程式碼處理, 對於程式碼的精簡有很大的幫助, 同時也降底程式 碼的複雜度. 程式碼只有 50 行 :) 當然, 其中 question[] 是為了縮短程式所用的技巧, 有點過分就是 ^^; 剩下的部分並沒有特別為了程式長度縮短而破壞程式的結 構與可讀性, 大致上與我平時寫程式的風格差不多 :) #include <stdio.h> #include <ctype.h> struct Data { char type; double base; double payrate[3]; } item[3]={{'O',100.0, {1.0,1.0,1.0}}, {'G',500.0, {0.8,0.8,1.0}}, {'E',1000.0,{1.0,1.0,0.5}}}; char question[4][1024]= {"Please input your user id type,\n" "O for normal user, G for government, E for enterprise:", "and input local area phone time in minutes:", "and input long distance phone time in seconds:", "and input international phone time in seconds:"}; int timeunit[3]={3,10,5}; int main(void) { char type[10]; int i,t; int id=-1; double pay=0.0; /* Get user id type */ puts(question[0]); gets(type); for(i=0;i<3;i++) if(toupper(type[0])==toupper(item[i].type)) id=i; if(id==-1) { printf("Unknown user id type\n"); return 1; } /* Read in user phone time, and compute */ for(i=0;i<3;i++) { puts(question[i+1]); scanf("%d",&t); pay+=item[id].payrate[i]*((t+timeunit[i]-1)/timeunit[i]); } if(pay<item[id].base) pay=item[id].base; /* Output how much money this user should pay */ printf("This user should pay %.2f dollars.\n",pay); return 0; } -- "靈感 = 經驗 + 嘗試 + 快速的計算能力" --- Ledia "靈感, 是實力的累積" --- untitled -- ※ 發信站: 批踢踢實業坊(ptt.twbbs.org) ◆ From: jun.csie.ntu.edu