fflush(stdin)和rewind(stdin)
2016-03-06 12:09
260 查看
#include <stdio.h> #include <math.h> int main() { double a, b, c, disc, x1, x2, p, q, i; do { scanf_s("a=%lf,b=%lf,c=%lf", &a, &b, &c); i = b*b - 4 * a*c; } while (i<0); printf("输入正确"); disc = b*b - 4 * a*c; p = -b / (2 * a); q = sqrt(disc) / (2 * a); x1 = p + q, x2 = p - q; printf("x1=%5.2f\nx2=%5.2f\n", x1, x2); return 0; }
在群中有人问了此例,算一元二次方程,scanf()在vs2015中不能用,所以我将其改为了scanf_s()。
当时我认为其输入的:
a=1,b=2,c=3
不满足其输入正确的条件,所以要接着输入a=?,b=?,c=?这些,然而并不能继续输入,按其他键无任何反应,有人回复用fflush(stdin);即可,即:
#include <stdio.h> #include <math.h> int main() { double a, b, c, disc, x1, x2, p, q, i; do { fflush(stdin); scanf_s("a=%lf,b=%lf,c=%lf", &a, &b, &c); i = b*b - 4 * a*c; } while (i<0); printf("输入正确"); disc = b*b - 4 * a*c; p = -b / (2 * a); q = sqrt(disc) / (2 * a); x1 = p + q, x2 = p - q; printf("x1=%5.2f\nx2=%5.2f\n", x1, x2); return 0; }
然而在我的vs2015上面仍不能运行,接着我去百度查询。
发生第二次循环无法输入的原因在于输入缓冲区的问题,在读入一个数或字符之后紧接着要读取,此时应该清除输入缓冲区,而fflush(stdin)无法在vs2015中运行,其主要因为该函数功能虽然为:清空输入缓冲区,为确保不影响后面的数据读取。但需注意的是此函数仅适用于部分编译器,如vc6,并非所有编译器都支持这个函数。最合适的做法是加rewind(stdin)。
#include <stdio.h> #include <math.h> int main() { double a, b, c, disc, x1, x2, p, q, i; do { rewind(stdin); scanf_s("a=%lf,b=%lf,c=%lf", &a, &b, &c); i = b*b - 4 * a*c; } while (i<0); printf("输入正确"); disc = b*b - 4 * a*c; p = -b / (2 * a); q = sqrt(disc) / (2 * a); x1 = p + q, x2 = p - q; printf("x1=%5.2f\nx2=%5.2f\n", x1, x2); return 0; }
或者在紧接着读取之前输出某些:
#include <stdio.h> #include <math.h> int main() { double a, b, c, disc, x1, x2, p, q, i; do { printf("输入a,b,c:"); scanf_s("%lf%lf%lf", &a, &b, &c); i = b*b - 4 * a*c; } while (i<0); printf("输入正确"); disc = b*b - 4 * a*c; p = -b / (2 * a); q = sqrt(disc) / (2 * a); x1 = p + q, x2 = p - q; printf("x1=%5.2f\nx2=%5.2f\n", x1, x2); return 0; }
相关文章推荐
- Clob类型转化String类型
- JS的构造及其事件注意点总结
- 排序算法之归并算法
- 何为“游戏性”?
- Android Sdk 和ADT Eclipse安装配置步骤
- POJ 2728 Desert King 01分数规划 最优比率生成树
- vim+python+OpenCV学习七 : Sobel算子、Laplacian算子和Canny边缘检测
- IBatis和Hibernate区别
- 音乐播放器的显示与隐藏
- Hibernate之HQL查询的一些例子
- Json格式化form表单里面需要提交的数据
- 安装Java jdk1.6或1.7的详细步骤和配置环境变量的另类办法
- 常用的视频格式mime设置
- 寒假近半个月的收获
- 学会使用listview的自定义baseadapter适配器
- 有意思的分支预测
- codeforces2016
- bzoj4236 JOIJOI
- javascript编程习惯总结
- 六种方式实现hibernate查询