繁体   English   中英

查找数组中的最大值、最小值和平均值

[英]Find the maximum, minimum, and average values in the array

在我的代码中,程序不允许输入负数,程序会停止读取,然后计算最大值、最小值和平均值。 那是我的代码

#include <stdio.h>

int main(void) {
  int age[10] = {0};              // initalized an array
  printf("Please enter ages: \n");  // allow user to enter numbers


  for (int i = 0 ;i < 10; i++) {
    scanf("%d",&age[i]);
    if (age[i] < 0) { // if it is negative number, it is should stop reading
      break;
    }
    else if (age[i] >= 0) {
      continue;
    }
  }
  int maximum = age[0];
  int minimum = age[0];
  float average = 0.0;
  int length = sizeof(age) / sizeof(age[0]);
  for (int j = 0; j < length; j++) {
    if (maximum < age[j]) {
      maximum = age[j];
    } 
    else if (minimum > age[j]) {
      minimum = age[j];
    }
    average += age[j];
  }

  average = average / length;
  printf("%d\n", maximum);
  printf("%d\n", minimum);
  printf("%.1f\n", average);

  return 0;
}

请输入年龄:5 -1 预期结果:max:5;min:5,average:5;

实际结果:最大值:5;最小值:-1,平均值:0.4;

这是我遇到的一个问题,代码不应该接受任何负值。

谢谢你们。 但如果我添加 age[i] = 0; 然后打破; 平均值将等于 0.5。

  • 你不需要数组。
  • 您不需要循环变量和长度。
  • 用起来更合适? : ? :用于更新最小值/最大值。
  • 你不需要两个循环
  • 你需要检查scanf()int返回值,它表示成功扫描的项目数,所以它应该是1 我将把它留给你/OP 添加(提示:用while -loop 替换for -loop 以避免再次添加单独的length变量)。
    int main(void)
    {
        printf("Please enter ages: \n");

        int minimum = INT_MAX;
        int maximum = 0;
        int sum = 0;
        int count = 0;

        for (count = 0; count < 10; count++)
        {
            int age;
            scanf("%d", &age);

            if (age < 0)
            { 
                break;
            }

            sum += age;

            minimum = (age < minimum) ? age : minimum;
            maximum = (age > maximum) ? age : maximum;
        }

        if (count > 0)
        {
            printf("Min: %d\n", minimum);
            printf("Max: %d\n", maximum);
            printf("Avg: %.1f\n", (float)sum / count);
        }
        else
        {
            printf("You didn't enter (valid) age(s).\n");
        }

        return 0;
    }

您的方法过于复杂和错误。

你要这个:

  ...
  int length = 0;    // declare length here and initialize to 0

  for (int i = 0; i < sizeof(age) / sizeof(age[0]); i++) {
    scanf("%d", &age[i]);

    if (age[i] < 0)  // if it is negative number, it is should stop reading
      break;

    length++;        // one more valid number
  }
  
  // now length contains the number of numbers entered
  // the rest of your code seems correct

您可能还需要处理没有输入数字的特殊情况,例如:唯一输入的是-1 当没有数字时,计算平均值或最大/最小数字是没有意义的。

一个可能的解决方案可能是:

(更正写在注释代码中)

#include <stdio.h>

int main(void){
  int arraySize = 10;
  int age[arraySize]; //initialize not required
  
  //the number of existing values inside the array (effective length)
  int length = 0;

  printf("Please enter ages: \n");  // allow user to enter numbers

  for(int i=0; i<arraySize; i++){
    scanf("%d",&age[i]);
    
    // if it is negative number, it is should stop reading
    if(age[i]<0){ break; }
    
    //the else-if is not required
    //but, if the compiler goes here,
    //it means that the value is acceptable, so
    length++;
  }

  int maximum = age[0];
  int minimum = age[0];
  float average = 0.0;
   
  for(int j=0; j<length; j++){
    if(maximum<age[j]){ maximum = age[j]; } 
    else if(minimum>age[j]) { minimum = age[j]; }
    average += age[j];
  }

  average = average / length;
  printf("%d\n", maximum);
  printf("%d\n", minimum);
  printf("%.1f\n", average);

  return 0;
}

OP 的主要问题是第二个循环迭代 10 次而不是i次(输入非负数的次数。


为了好玩,让我们尝试一个非浮点解决方案,因为它确实是一个整数问题。

不需要用于存储值的数组。

#include <limits.h>
#include <stdio.h>

int main(void) {
  // Keep track of 4 things
  int min = INT_MAX; // Set min to the max int value.
  int max = INT_MIN;
  long long sum = 0; // Use wide type to cope with sum of extreme ages.
  int count = 0;

  #define INPUT_N 10

  printf("Please enter ages: \n");
  
  for (count = 0; count < INPUT_N; count++) {
    int age;
    if (scanf("%d", &age) != 1) {
      fprintf(stderr, "Missing numeric input.");
      return EXIT_FAILURE;
    }
    if (age < 0) {
      break;
    }

    if (age < min) min = age;
    if (age > max) max = age;
    sum += age;
  }

  if (count == 0) {
    fprintf(stderr, "No input.");
    return EXIT_FAILURE;
  }

  printf("Maximum: %d\n", max);
  printf("Minimum: %d\n", min);

  // Could use FP and 
  // printf("Average: %.1f\n", 1.0 *sum / count);
  // But for fun, how about a non-FP approach?
 
  #define SCALE 10
  #define SCALE_LOG 1
  sum *= SCALE; // Scale by 10 since we want 1 decimal place.
  // Perform a rounded divide by `count`
  long long average_scaled = (sum + count/2) / count;
  // Print the whole and fraction parts
  printf("Average: %lld.%.*lld\n", 
      average_scaled / SCALE, SCALE_LOG, average_scaled % SCALE);

  return 0;
}

首先,你必须记录你输入了多少个正数。 那么length的值将是正确的。

其次,对于第二个for循环, j必须小于正年龄数。 因此,您不会将负age[j]添加到average

您可以简单地修改第二个 for 循环。

#include <stdio.h>

int main(void) {
  int age[10] = {0};              // initalized an array
  printf("Please enter ages: \n");  // allow user to enter numbers


  int length = 0;

  for (int i = 0 ;i < 10; i++) {
    scanf("%d",&age[i]);
    if (age[i] < 0) { // if it is negative number, it is should stop reading
      break;
    }
    else if (age[i] >= 0) {
      length++;
      continue;
    }
  }
  int maximum = age[0];
  int minimum = age[0];
  float average = 0.0;

for (int j = 0; j < length; j++) {
    if (maximum < age[j]) {
      maximum = age[j];
    } 
    else if (minimum > age[j]) {
      minimum = age[j];
    }

    if ( age[j] > 0.0 )
    {
      average += age[j];
    }
  }

  average = average / length;
  printf("%d\n", maximum);
  printf("%d\n", minimum);
  printf("%.1f\n", average);

  return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM