zl程序教程

您现在的位置是:首页 >  其他

当前栏目

continue跳過循環(skippaart程序),接受設定的合法分數來進行平均分求值,并展現最高分,最低分

2023-04-18 15:21:16 时间
 1 #include<stdio.h>
 2 int main()
 3 {
 4      const float MIN = 0.0f;   //分數下限是0分
 5      const float MAX = 100.0f; //分數上限是100分
 6 
 7      float score;
 8      float total = 0.0f;       //求總分
 9      int n = 0;                //接受符合規定分數的個數
10      float min = MIN;          //分數下限
11      float max = MAX;          //分數上限
12 
13      printf("Enter the first score (q to quit): ");
14      while(scanf("%f",&score)==1)
15      {
16          if(score < MIN || score > MAX)
17          {
18              printf("%0.1f is an invalid value. Try again: ",score);
19              continue;   //跳轉至while循環的測試條件
20              //continue語句讓程序跳過有效輸入部分的代碼。程序開始下一輪循環,準備讀取下一個輸入值。
21          }
22          printf("Accepting %0.1f:
",score);
23          min = (score < min) ? score : min;
24          max = (score > max) ? score : max;
25          total += score;
26          n++;                  //統計一共輸入了多少分數(計數器)
27          printf("Enter next score (q to quit): ");
28      }
29      if (n > 0)
30      {
31          printf("Average of %d scores is %0.1f.
", n, total / n);
32          printf("Low = %0.1f, high = %0.1f
", min, max);
33      }
34      else
35         printf("No valid scores were entered.
");
36 
37     return 0;
38 }
39 /*
40 輸出樣例
41 
42 Enter the first score (q to quit): 188
43 188.0 is an invalid value. Try again: 90
44 Accepting 90.0:
45 Enter next score (q to quit): 12
46 Accepting 12.0:
47 Enter next score (q to quit): 100
48 Accepting 100.0:
49 Enter next score (q to quit): 85
50 Accepting 85.0:
51 Enter next score (q to quit): q
52 Average of 4 scores is 71.8.
53 Low = 12.0, high = 100.0
54 
55 */

爲什麽第10,11行要這樣設置?

float min = MIN;          //分數下限
float max = MAX;          //分數上限
如果在第10,第11行設置成:
float min = MIN;
float max = MAX;
則會導致地23行的計算會讓min最終計算的值永遠為0,不會在出現比0小的數字(沒有負數分數)。
而float max = MAX 導致的問題是在第24行最終最大分數的計算會一直是100.不會出現比100再大的分數(百分制為例)。
所以min,max的本質含義是min和滿分比較時來鎖定最小值,max和0分比較來鎖定最大值。
const float MIN = 0.0f;   //分數下限是0分
const float MAX = 100.0f; //分數上限是100分
而上方的const變量(MIN,MAX)本質意義是一個宏,是爲了後期方便維護程序,修改數值方便,而不能直接去使用,與min,max是有著不同的意義