打印出最高数字的C程序

标签 c

所以我需要编写一个 C 程序来打印出输入的最大数字。 如果输入为空,则不应打印任何内容。 如果输入包含数字以外的任何内容,则不应打印任何内容。 例子: 如果输入是 1 2 3 2 1 它应该打印出 3。 如果输入是 1 2 a 2 1 它不应该打印出任何东西。

这是我到目前为止得到的:

#include <stdio.h>

int main()
{
    int res, max, x;

    res = scanf("%d", &max);
    if (res == 1) {
        while(res != EOF)
        {
            res = scanf("%d", &x);
            if (x > max)
            {
                max=x;
            }
        }
        printf("%d", max);
    } else {
        return 0;
    }
    return 0;
}

所以我的问题是,如果它包含上面示例中的字母,我如何让它不打印任何内容。 提前致谢!

最佳答案

#include <stdio.h>

int main()
{
   int max, x;

   if (scanf("%d", &max) != 1)
   {
      // If there is no number, exit the program.
      return 0;
   }

   while ( scanf("%d", &x) == 1 )
   {
      if (x > max)
      {
         max=x;
      }
   }

   // If we came to the EOF, we didn't see any bad input.
   if ( feof(stdin) )
   {
      printf("Max: %d\n", max);
   }

   return 0;
}

关于打印出最高数字的C程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27948369/

相关文章:

将 16 位哈希值复制到 32 位数组上

c - 在C程序中获取系统命令输出

c - 如何在Unix/Linux下运行自己编译的程序?

c - 使用 memset() 将动态分配的结构初始化为全 0 是一个好习惯吗?如果是,有什么好处?

c - 自修改代码,复制/跳入堆失败

c++ - "C-style array"是什么意思,它与 std::array (C++ 风格)有何不同?

c - 让Make自动将头文件中的Objs编译到存档中,然后编译到主程序中

c - 全局变量是否被视为语句?

c - 带有 srand 的函数将无法编译

c - printf 是否支持 C 中的函数重载?