无法从阵列输出正确的最大值和最小值

时间:2017-02-12 15:24:45

标签: c arrays max min

我编写了一个程序,让用户选择输入温度的天数(3到10之间),然后输入每天的高温和低温。我遇到的问题是我必须在这些输入中输出最高的高温和最低的低温,以及这个高低发生的那一天。我的代码似乎总是跳到最后一天,即使它不包含最高或最低,并且日总是比输出的天数大一天。这是我的代码:

#include <stdio.h>

int main (void)
{
    int i;
    int limit;
    int day[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int high[10],low[10];

    printf("---===IPC Temperature Analyzer V2.0===---\n");

    printf("Please enter the number of days between 3 and 10, inclusive: ");
    scanf("%d", &limit);
    while (limit <= 2 || limit >= 11) {
            printf("Invalid entry, please enter a number between 3 and 10,   inclusive: ");
            scanf("%d", &limit);
    }

    for(i = 0;i < limit; i++) {
            printf("Day %d - High: ", day[i]);
            scanf("%d", &high[i]);
            printf("Day %d - Low: ", day[i]);
            scanf("%d", &low[i]);
    }

    printf("\nDay Hi Low\n");
    for (i = 0; i < limit; i++) {
            printf("%d   %d    %d\n", day[i], high[i], low[i]);
    }

    int max = 0;
    int min = 0;

    for (i = 0; i < limit; i++) {
            if (high[max] < high[i])
            max = i;
            if (low[min] < low[i])
            min = i;

    }

    printf("\nHighest temperature was: %d on day %d", high[max], day[max]);

    printf("\nLowest temperature was: %d on day %d ", low[min], day[min]);


    return 0;

}

2 个答案:

答案 0 :(得分:1)

从第;行和if (max < high[i]);

中删除if (min > low[i]);

你也可以把这两个循环结合起来

for (i = 0; i < limit; i++) {
        if (max < high[i])
        max = high[i];
}

printf("\nHighest temperature was: %d on day %d", max, day[i]);

for (i = 0; i < limit; i++) {
        if (min > low[i])
        min = low[i];
}

像这样进入一个for循环

for (i = 0; i < limit; i++) {
        if (max < high[i])
            max = high[i]
        if (min > low[i])
            min = low[i];
}

答案 1 :(得分:1)

您还需要在阅读输入后初始化最小值和最大值。

CREATE TABLE `Laptop` (
`serial number ` INT( 20 ) NOT NULL ,
`Device Model` VARCHAR( 20 ) NOT NULL ,
`Device Manufacturer` VARCHAR( 20 ) NOT NULL ,
`Device Color` VARCHAR( 20 ) NOT NULL ,
`Screen size` DOUBLE( 20 ) NOT NULL ,
`Phone` DOUBLE( 20 ) NOT NULL ,
`Id` INT( 20 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
UNIQUE (
`serial number ` 
)
) ENGINE = innodb