C程序找到第二大数字

时间:2019-12-11 15:10:42

标签: c

我正在尝试找到该程序中第二大的数字,请尝试帮助我:(

#include <stdio.h>

#define VALUE_TO_STOP -999

int main(void)
{
    int num,num2,max,secondMax = 0;

    printf("Enter a number (-999 to stop): ");
    scanf("%d", &num);

    while(num2 != VALUE_TO_STOP)
    {
        printf("Enter a number (-999 for end): ");
        scanf("%d", &num2);

        if(num2 > num || num2 > max)
        {
            max = num2;
        }

        if(num2 > secondMax && num2 < max)
        {
            secondMax = num2;
        }
    }

    printf("First max: %d", max);
    printf("\nThe second max: %d", secondMax);

    return 0;
}

1 个答案:

答案 0 :(得分:-1)

我已修正您的代码。 首先,您必须初始化int max

第二,您必须在从用户获得 num1 之后(在while循环之前)分配int max

第三,您必须更改 if,else if 语句的条件。

#include <stdio.h>
#define VALUE_TO_STOP -999

int main(void)
{
 int num,num2,max=0,secondMax = 0;

printf("Enter a number (-999 to stop): ");
scanf("%d", &num);
max=num;
while(num2 != VALUE_TO_STOP)
{
    printf("Enter a number (-999 for end): ");
    scanf("%d", &num2);

    if(num2 > max)
    {
        secondMax=max;
        max = num2;
    }

    if(num2 > secondMax && num2 !=max)
    {
        secondMax = num2;
    }
}

printf("First max: %d", max);
printf("\nThe second max: %d", secondMax);

return 0;
}