查找在C中终止于0的数组的最大,最小,和和平均值

时间:2019-06-16 19:28:36

标签: c arrays

所以基本上我必须找到零终止数组的最大,最小和之和。

我得到了平均值和总和,但没有找到最大的最小值,正数和负数的平均值。输入0后,数组停止。

#include <stdio.h>

int main() {
    int c = 0, n, array[100], large, small;
    float sum = 0;
    //for (c = 0; c < n; n++) {
    do {
        c++;
        printf("\nEnter number:");
        scanf("%d", &array[c]);
        sum += array[c];
    } while (array[c] != 0);

    if (array[c] > large) { large = array[c]; }
    if (array[c] < small) { small = array[c]; }
    if (array[c] == 0) {
        printf("\n Sum = %.2f\n", sum);
        printf("\n Average = %.2f", sum / (c - 1));
        printf("\n Largest %d", large);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:1)

您的代码中存在多个问题:

  • 数组索引从C中的0开始,在存储值之前,不应该递增c
  • 您实际上不需要存储值,只需对它们进行足够的计数即可
  • 您应该从读取的第一个值初始化largesmall
  • 您应该测试scanf()的返回值以检测无效的输入并避免未定义的行为

这是更正的版本:

#include <stdio.h>

int main() {
    int c, n, large, small;
    double sum = 0;
    for (c = 0;; c++) {
        printf("Enter number: ");
        if (scanf("%d", &n) != 1 || n == 0)
            break;
        sum += n;
        if (c == 0 || n > large) {
            large = n;
        }
        if (c == 0 || n < small) {
            small = n;
        }
    }
    if (c == 0) {
        printf("no numbers\n");
    } else {
        printf("Smallest: %d\n", small);
        printf("Largest: %d\n", large);
        printf("Sum = %f\n", sum);
        printf("Average = %.2f\n", sum / c);
    }
    return 0;
}

为了说明上面的代码如何在没有本地数组的情况下工作,下面是一个带有数组的中间版本并附带注释:

#include <stdio.h>

int main() {
    int c, n, i, array[100], large, small;
    double sum;
    for (c = 0; c < 100; c++) {     // loop reading into array, stop at array size
        printf("Enter number: ");
        if (scanf("%d", &n) != 1)   // read a number, stop on failure
            break;
        if (n == 0)                 // stop when reading a 0
            break;
        array[c] = n;
    }
    if (c == 0) {
        printf("no numbers\n");
        return 0;
    }
    // initialize variables from first entry
    sum = array[0];
    large = small = array[0];
    // loop over remaining entries and update variables
    for (i = 1; i < c; i++) {
        sum += array[i];
        if (large < array[i]) {
            large = array[i];
        }
        if (small > array[i]) {
            small = array[i];
        }
    }
    printf("Smallest: %d\n", small);
    printf("Largest: %d\n", large);
    printf("Sum = %f\n", sum);
    printf("Average = %.2f\n", sum / c);
    return 0;
}