打印出最高编号的C程序

时间:2015-01-14 16:58:04

标签: 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;
}

所以我的问题是,如果它包含上面例子中的字母,我如何使它打印出来。 提前谢谢!

3 个答案:

答案 0 :(得分:2)

#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;
}

答案 1 :(得分:1)

#include <stdio.h>

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

    if(1 != scanf("%d", &max))
        return -1;

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

答案 2 :(得分:-1)

如果输入为数字,scanf将返回1

#include <stdio.h>

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

    if (scanf("%d", &max) != 1)
        return -1;
    x = max;
    do {
        result = scanf("%d[^\n]", &x);
        if ((result != EOF) && (result != 1))
            return 0;
        else if ((result != EOF) && (x > max))
            max = x;
    } while (result != EOF);

    printf("\n\nMaximum Input : %d\n", max);
    return 0;
}

当输入无效时,前一个程序将停止,即不是数字。

相关问题