2013-10-03 33 views
-1

我的程序假設讀取多個輸入並顯示最小值,最大值,總和和平均值。它應該是這樣的:在c中使用scanf和循環輸入多個雙精度數據,並且沒有數組循環

輸入:

2.5 5 3.5 4.5 jfkjk 

輸出:

min is 2.5 
max is 5 
sum is 15.5 
average is 3.875 

該方案被認爲當它到達一個非數字或一個換行符退出。用戶可以輸入儘可能多的數字。我不能使用數組,並且必須使用循環。 這是我的計劃是什麼樣子:

void numbers() 
     { 
     double digit; 
     double sum = 0; 
     double avg = 0; 
     double max; 
     double min; 
     unsigned count = 0; 
     //int c; 
     max = 0; 
     printf("Input:"); 

     do { 
      scanf("%lf", &digit); 

      min = digit; 
      if(max < digit) 
       digit = max; 
      if(min < digit) 
       digit = min; 
      sum += digit; 
      count++; 
      avg = sum/count; 
     } while(scanf("%lf", &digit)==1) 

     printf(" min is %lf max is %lf sum is %lf avg is %lf count is %u", min, max, sum, avg, count); 
     } 

打印出:

Input:2.2 2.3 5 3.5 blah 
min is 3.500000 max is 0.000000 sum is 0.000000 avg is 0.000000 count is 4 
+0

先用正確的輸入檢查你的程序,然後嘗試further.see Liho答案,並使用一個scanf函數與環路和移動scanf函數內部循環來之前。 – Gangadhar

回答

2

有2個隱藏在你的代碼非常不愉快的錯誤:

  • 方式minmax是(不)在迭代數字時更新

    這樣:

    if(max < digit) 
        digit = max; 
    if(min < digit)   // <-- the comparison for min is incorrect as well 
        digit = min; 
    

    應該是:

    if(max < digit) 
        max = digit; 
    if(min > digit)   
        min = digit; 
    

    ,因爲要更新min/max,而不是已經閱讀digit。你的循環

  • 邏輯此:

    do { 
        scanf("%lf", &digit); 
        ... 
    } while(scanf("%lf", &digit)==1) 
    

    應該是:

    while(scanf("%lf", &digit)==1) { 
        ... 
    } 
    
+0

通過這些編輯,'min'不被初始化。建議'double min = +大數字'和'max =大數字'。 – chux

0

如果是真正重要的:
- 1)用戶可輸入儘可能多的數字。
- 2)退出時,它到達一個非數字或換行符。
- 3)沒有陣列。
然後閱讀數據是具有挑戰性的。

我們必須處理的推移和輸入線路.....
我們必須換行\n和其他空白char區分。

按照OP風格,讓我們手動執行空格分析,然後讓scanf()讀取數字。

#include<stdio.h> 
#include<ctype.h> 

    ... 
    double sum = 0.0; 
    double avg = 0.0; 
    double max = 0.0; 
    double min = 0.0; 
    unsigned count = 0; 
    int done = 0; 
    while (1) { 
    double x; 
    int ch; 
    do { 
     ch = getchar(); 
     if ((ch == '\n') || (ch == EOF)) { 
     done = 1; 
     break; 
     } 
    } while (isspace(ch)); 
    if (done || (1 != scanf("%lf", &x))) break; 
    // Cope with first `x`. 
    // Could instead be done with `max` initialized to -DBL_MAX, min = DBL_MIN 
    if (count++ == 0) { 
     min = max = x; 
    } else { 
     if (x < min) min = x; 
     if (x > max) min = x; 
    } 
    sum += x; 
    // OP had the following inside the loop - nicely avoids potential /0 outside loop 
    avg = sum/count; 
    }