Advertisement
uopspop

Untitled

Dec 26th, 2016
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.  
  6.     int a = 2,b = 5,ans = 0;
  7.  
  8.     printf("1: 加法\n");
  9.     printf("3: 乘法\n");
  10.  
  11.     // 拿到n為止才結束這個迴圈:
  12.     int n;
  13.     int count;
  14.     while( (count = scanf(" %d",&n)) != 1)
  15.     {
  16.         printf("1: 加法\n");
  17.         printf("3: 乘法\n");
  18.         printf("count: %d\n",count);
  19.         if (count == 0)
  20.         {
  21.             // 重要: 避免scanf()出現無限迴圈的解決方式:
  22.             int ch;
  23.             // 當fgetc拿到的下一個字元不是'\n'或者EOF的話,就繼續拿,把所有多餘的input都清掉:
  24.             while (((ch = fgetc(stdin)) != '\n') && (ch != EOF)){}
  25.         }
  26.  
  27.     }// end of while
  28.     // end of 拿到n為止才結束這個迴圈
  29.  
  30.     // 開始計算
  31.     switch(n)
  32.     {
  33.     case 1:
  34.         ans = a + b;
  35.         break;
  36.     case 3:
  37.         ans = a * b;
  38.         break;
  39.     default:
  40.         ans = 0;
  41.         break;
  42.     }
  43.     // end of 開始計算
  44.  
  45.     // 呈現結果
  46.     printf("計算結果: %d\n", ans);
  47.  
  48.  
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement