您的位置:首页 > 其它

[分支循环](补)用分支结构实现输出三个数中的最大值

2012-11-01 13:44 429 查看
环境:OS 10.7 + Xcode 4.2

想法:用scanf()的返回检测输入数据的合法性,同时清空键盘缓冲区以免错误的输入数据影响下次输入。

代码如下:

#include<stdio.h>

int bigger(int x, int y);
int bigger(int x, int y)
{
if (x > y)
return x;
else return y;
}

int main(void)
{
int a, b, c;
int max, mark = 1;
int check;

while (mark)
{
printf("Please enter three numbers(all zero to end): ");
//check validity of the input data
check = scanf("%d %d %d", &a, &b, &c);
setbuf(stdin, NULL);     //rewind(stdin);
if (check != 3)
{
printf("Input Error!\n");
continue;
}
//terminal condition
if (a == 0 && b == 0 && c == 0)
{
mark = 0;
continue;
}

max = bigger(a, bigger(b, c));
printf("The biggest numbers is %d\n", max);
}

printf("Thank you! ByeBye!\n");
return 0;
}


状况:

Please enter three numbers(all zero to end): a b c
Input Error!
Please enter three numbers(all zero to end): a a a
Input Error!
Please enter three numbers(all zero to end): Input Error!
Please enter three numbers(all zero to end): Input Error!
Please enter three numbers(all zero to end): a 3 a
Input Error!
Please enter three numbers(all zero to end): Input Error!
Please enter three numbers(all zero to end):


分析、小结:

(1)scanf()遇到错误输入就返回,没有读入的数据继续存留在键盘缓冲区。

(2)在网上找了三个函数用来清空键盘缓冲区:

fflush(stdin);       遇到a a a的输入就进入死循环,其他没试。。。

rewind(stdin);      无异常。。。

setbuf(stdin, NULL);    状况如上。。而且这个函数也并非清空键盘缓冲区,暂时没弄明白作用,还需努力。。  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: