[分支循环](补)用分支结构实现输出三个数中的最大值
2012-11-01 13:44
429 查看
环境:OS 10.7 + Xcode 4.2
想法:用scanf()的返回检测输入数据的合法性,同时清空键盘缓冲区以免错误的输入数据影响下次输入。
代码如下:
状况:
分析、小结:
(1)scanf()遇到错误输入就返回,没有读入的数据继续存留在键盘缓冲区。
(2)在网上找了三个函数用来清空键盘缓冲区:
fflush(stdin); 遇到a a a的输入就进入死循环,其他没试。。。
rewind(stdin); 无异常。。。
setbuf(stdin, NULL); 状况如上。。而且这个函数也并非清空键盘缓冲区,暂时没弄明白作用,还需努力。。
想法:用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); 状况如上。。而且这个函数也并非清空键盘缓冲区,暂时没弄明白作用,还需努力。。
相关文章推荐
- c语言:求三个数中的最大值(双分支结构)
- thinkPHP实现递归循环栏目并按照树形结构无限极输出的方法
- 作业三-应用分支与循环结构解决问题——.输入一个整数 x,计算并输出下列分段函数 sign(x) 的值
- 2014-C第1周项目——初步体验分支结构和循环结构的程序设计 3 三数中的最大值
- 实现三个数的大小比较,并输出最大值
- 第七课,分支结构程序体验|三个整数输出最大值 |计算两数正差值|周薪计算
- thinkPHP实现递归循环栏目并按照树形结构无限极输出的方法
- 第七课,分支结构程序体验|三个整数输出最大值
- PHP实现循环队列(顺序结构)
- 用JavaScript脚本语言设计并实现一个函数,将三位数重新排列输出最大值
- 在多个服务器跑程序经验之批处理顺序、分支、循环结构
- 数据结构基础(12) --双向循环链表的设计与实现
- for循环实现各种图形输出
- ARM汇编语言 实现多分支switch结构的一点感想
- ajax实现json循环输出结果
- OJ第二批——Problem A:C++类实现最大数的输出
- python 中while 使用else实现双分支循环判断
- java基础七(循环和分支结构)
- PHP学习笔记(25)流程分支控制结构 (26)PHP实现简单计算器
- 2012704-分支结构练习(输入一个成绩,输出其等级)