所以我需要编写一个 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/