c - 我需要帮助弄清楚为什么这不起作用。 (C)

标签 c

This is what i get该代码需要打印最多2个数字,当输入-999时代码需要停止。 我尝试了所有方法,但大多数时候我得到了最大数字,但没有得到第二个最大数字。

#include <stdio.h>



int main ()
{
    int x = 0;
    int max = 0;
    int max2 = 0;
    int y = 0;
    int flag = 0; 
    do
    {
        printf("Enter the number  -999 to stop: ");
        scanf("%d", &x);
        if (x != -999)
        {
            if (x > max)
            {
                max = x;  
                max2 = y;   
            }
            printf("Enter the number  -999 to stop: ");                      
            scanf("%d", &y);
            if (y != -999)
            {
                if (y > max)
                {   
                    max = y;
                    max2 = x;
                }
            }
            else
            {
                flag = 1;
            }
        }
        else
        {
            flag = 1;
        }
    }
    while (flag == 0);
    printf("The max number is: %d\n", max);
    printf("The second max number is: %d\n", max2);

    return 0;
}

最佳答案

#include <stdio.h>



int main ()
{
    int x = 0;
    int max = 0;
    int max2 = 0;
    int flag = 0; 

 do
 {
     printf("Enter the number  -999 to stop: ");
     scanf("%d", &x);
     if (x != -999)
     {   // bigger than max?
         if (x > max)
         {   
             // since the new max is x and the old max is bigger than max2
             max2 = max;
             max = x;     
         }
         // bigger than max2?
         else if (x > max2)
         {   
            max2 = x;
         }

     }
     else // exit loop
     {
         flag = 1;
     }
    }
 while (flag == 0);
 printf("The max number is: %d\n", max);
 printf("The second max number is: %d\n", max2);

 return 0;
}

关于c - 我需要帮助弄清楚为什么这不起作用。 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53571447/

相关文章:

libcurl 可以用于发出多个并发请求吗?

c - 静态变量的内存位置

c - 如果线程在释放内存之前被杀死,如何释放线程分配的内存?

c - 为什么我在 while 循环中遇到这样的限制时会出现段错误?

c++ - 这是合法的 C++ 代码吗?

c - 函数参数中的字符串

c - inet_pton() 的第三个参数是什么?

c - 在 GValueArray 类型上使用 "g_array_index()"

c - EVP_MD_CTX "error: storage size of ‘ctx’ 未知”

c - Break 语句的行为