返回列表 回復 發帖

[討論] [C語言]清大資工程式設計作業五解答

[討論] [C語言]清大資工程式設計作業五解答

題目
Anna從座標 (0,0) 出發,上午向東走 5km 休息,下午再向北走 2km 休息。
你的程式要藉由 while 迴圈讓使用者可重複輸入天數n,若n非正整數,則結束這個程式 (類似範例 E05_04.c);
若 n 是正整數則另外呼叫自己寫的function (類似 E05_10.c,宣告成 void print_pos(int n);),
用它在螢幕上顯示出Anna每天中午和晚上停留的位置座標 (向東向北為正)。

plz input the number of days: 2
(5, 0) (5, 2)
(10, 2) (10, 4)
plz input the number of days: 5
(5, 0) (5, 2)
(10, 2) (10, 4)
(15, 4) (15, 6)
(20, 6) (20, 8)
(25, 8) (25, 10)
plz input the number of days: 0
Done.
解答
基本上解答有很多種寫法,我寫的這是最簡單的方法
事實上還有更簡潔的寫法,歡迎大家貼一下自己的寫法
  1. #include <stdio.h>
  2. void print_pos(int n);
  3. int main(void)
  4. {
  5.     int day;
  6.     printf("lease input the number of days : ");
  7.     scanf("%d", &day);
  8.     while(day > 0)
  9.     {
  10.               print_pos(day);
  11.               printf("lease input the number of days : ");
  12.               scanf("%d", &day);
  13.     }
  14.    
  15.     printf("Done!");
  16.    
  17.     return 0;
  18. }
  19. void print_pos(int n)
  20. {
  21.      int x1=5, y1=0, x2=5, y2=2, i=1;
  22.      
  23.      while(i < n+1)
  24.      {
  25.              printf("(%d,%d) (%d,%d)\n", x1, y1, x2, y2);
  26.              x1 = x1 + 5;
  27.              y1 = y1 + 2;
  28.              x2 = x2 + 5;
  29.              y2 = y2 + 2;
  30.              i++;
  31.      }
  32. }
複製代碼
[ 本帖最後由 Eason 於 2007-10-29 15:51 編輯 ]
返回列表