【问题标题】:How to find a minimum?如何找到最小值?
【发布时间】:2020-11-07 19:25:48
【问题描述】:

我需要让用户输入 7 到 12 ([7;12]) 之间的 N(数字)。然后,我需要让用户输入数字的数量,应该等于N。然后,我需要输出这些数字的总和,找到平均值,最小值和最大值。 它工作得很好,除了最低限度。当数字从 1 开始计数时,我的程序显示最小值为 0。谢谢你...

#include <stdio.h>

int main(void) {
  int i = 0;
  int N;
  float numbers;
  float sum = 0;
  float average, min, max;

  printf("Choose a number between 7 and 12: ");
  scanf("%d", &N);

  if (N >= 7 && N <= 12) {
    printf("You have chosen: %d\n", N);
    printf("Now choose the amount of N numbers you have chosen: ");

    for (i = 0; i < N; i++) {
      numbers = N; // the numbers the user enters must be
                   // strictly == N
      scanf("%f", &numbers);
      sum = sum + numbers;
      average = sum / numbers;

      if (numbers < min) {
        min = numbers;
      }

      if (numbers > max) {
        max = numbers;
      }
    }

    printf("The sum of your numbers is: %f\n The average of "
           "numbers: %f\n The max: %f\n The min: %f\n",
           sum, average, max, min);
  }
}

输出是:

    Choose a number between 7 and 12: 7                                                                                           
You have chosen: 7                                                                                                            
Now choose the amount of N numbers you have chosen: 1                                                                         
2                                                                                                                             
3                                                                                                                             
4                                                                                                                             
5                                                                                                                             
6                                                                                                                             
7                                                                                                                             
The sum of your numbers is: 28.000000                                                                                         
 The average of numbers: 4.000000                                                                                             
 The max: 7.000000                                                                                                            
 The min: 0.000000 

【问题讨论】:

  • 将 min 初始化为较大的值,将 max 初始化为较小的值。或者当输入数同时为最小值和最大值时,在第一次迭代时设置初始值。
  • 有可能,写一段代码

标签: c


【解决方案1】:

您的minmax 值未初始化使用。在您的平台/编译器上,似乎这些默认初始化为零,但 C 标准不要求这样做。

要解决此问题,只需将这些变量(在它们声明时)初始化为不能成为最终值的值(如 FLT_MAX 常量的 +/- 值,在 &lt;float.h&gt; 中定义):

    //...
    float average, min = FLT_MAX, max = -FLT_MAX;
    //...

【讨论】:

  • 另外,即使您将最小值初始化为 0,如果所有输入数据都是正数,您也永远不会得到实际最小值,因为初始值较小。
  • @starturtle 确实。这就是为什么我也避免使用0FLT_MIN 来初始化max 值的诱惑!如果所有输入数字都是负数,那将失败。
  • -FLT_MAX,因为语义与整数不同。的确。 叹息
  • 旁白:INFfloat 更大。
【解决方案2】:

我会以完全不同的方式来解决这个问题。将数字存储在数组中,然后对其进行排序。这是一个使用整数的示例,但很容易修改为浮点使用。

#include <stdio.h>

// Bubble sort
void bubbleSort (int *numArray, int numElements) {
    int sorted = 0, temp;
    while (!sorted) {
        // Set this flag here
        sorted = 1;
        for (int i = 0; i < numElements - 1; i++) {
            // Swaps the numbers
            if (numArray [i] > numArray [i + 1]) {
                temp = numArray [i];
                numArray [i] = numArray [i + 1];
                numArray [i + 1] = temp;
                sorted = 0;
            }
        }
    }
}

float calcAverage (int numArray [], int numElements) {
  float avg = 0;
  for (int i = 0; i < numElements; i++) avg += numArray [i];

  return avg / numElements;
}

int main() {
    int numElements = 0;
    // Ensure they actually enter a number!
    while (numElements < 7 || numElements > 12) {
        printf ("Please enter a number between 7 and 12: ");
        // Input validation is always important in my opinion.
        if (!scanf ("%d", &numElements)) {
            printf ("ERROR: NaN value passed! ");
        }
        else if (numElements < 7 || numElements > 12) printf ("ERROR: Invalid number! ");
        // Clear the buffer
        while (getchar() != '\n');
    }

    printf ("You have chosen: %d.\n", numElements);
    
    // Create our array and store our current number.
    int numArray [numElements], fGood;

    for (int i = 0; i < numElements; i++) {
      // Reset this flag at the beginning of the loop
      fGood = 0;

      while (!fGood) {
        printf ("Please enter value %d: ", i + 1);
        // Assume it's a good value
        fGood = 1;

        if (!scanf ("%d", &numArray [i])) {
          printf ("ERROR: Invalid value passed! ");
        }
        while (getchar() != '\n');
      }
    }

    bubbleSort (numArray, numElements);
    printf ("Average of entered numbers: %.2f\nMinimum value: %d\nMaximum value: %d\n", calcAverage(numArray, numElements), numArray [0], numArray [numElements - 1]);

    return 0;
}
  

【讨论】:

  • 有创意,但过于复杂,肯定会在代码审查时被击落。
  • OP 的值为float。此处未通过int 示例解决重要差异(无穷大,NaN)。 IAC,标准C库qsort()肯定比bubbleSort()效率更高。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-24
  • 2023-03-18
  • 1970-01-01
  • 2020-10-17
  • 2021-03-20
相关资源
最近更新 更多