OJ编程之多组输入----牛客网----BC41 你是天才吗?
题目要求:
错误代码:
#include <stdio.h>
int main()
{
int IQ = 0;
while(1)
{
scanf("%d",&IQ)
if(IQ >= 140)
{
printf("Genius\n");
}
}
return 0;
}
当我们写下这段代码时,OJ会报错,代码不通过
分析原因:
这是由于陷入死循环无法跳出
解决思路:
我们可以知道scanf这个函数返回类型为int整型
其返回值为接收到数据的个数,读取失败时返回EOF(相当于-1)
解决方法:
在本题中我们需要多组输入,每组输入一个数据,所以成功接收到一个数据返回1(成功接收数据的返回值一定是非-1的)
所以有两种表示方法:
#include <stdio.h>
int main()
{
int IQ = 0;
while(scanf("%d",&IQ) == 1)
{
if(IQ >= 140)
{
printf("Genius\n");
}
}
return 0;
}
#include <stdio.h>
int main()
{
int IQ = 0;
while(scanf("%d",&IQ) != EOF)
{
if(IQ >= 140)
{
printf("Genius\n");
}
}
return 0;
}