-1

My program is suppose to read multiple inputs and display the min, max, sum and the average. It is supposed to look like this:

Input:

2.5 5 3.5 4.5 jfkjk

output:

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

The program is supposed to quit when it reaches a non-number or a newline. The user can input as many numbers as they like. I cannot use arrays and must use loops. This is what my program looks like:

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);
      }

prints out:

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
4

2 回答 2

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 ) {
        ...
    } 
    
于 2013-10-03T20:11:33.933 回答
0

如果真的很重要:
-- 1) 用户可以输入任意数量的数字。
-- 2) 到达非数字或换行时退出。
-- 3) 没有数组。
那么读取数据是具有挑战性的。

我们必须处理一个连续不断的输入行......
我们必须区分 new-line\n和其他 white-space 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;  
  }
于 2013-10-03T22:29:10.260 回答