c - 使用 scanf 时出错:使用浮点数忽略返回值
问题描述
这是我的代码,我不确定为什么每次尝试测试时都会出错。它一直说 scanf 忽略了返回值
#include <stdio.h>
#include <math.h>
int main(void) {
float money, tax, result;
printf("Enter the amount of money.");
scanf("%f", &money);
tax = 0.05 * money;
result = tax + money;
printf("With tax added: $%f", result);
return 0;
}
解决方案
这是因为返回值被忽略了。
您应该检查返回值scanf()
以检查读数是否成功。
#include <stdio.h>
#include <math.h>
int main(void) {
float money, tax, result;
printf("Enter the amount of money.");
if (scanf("%f", &money) != 1) {
fputs("read error!\n", stderr);
return 1;
}
tax = 0.05 * money;
result = tax + money;
printf("With tax added: $%f", result);
return 0;
}
推荐阅读
- r - 分组后的 R 百分比图
- css - 左对齐但居中内容
- angularjs - 如何在 1.2.29 版本之后使用 ng-controller?
- python - 用 pandas 绘制大型数据集
- unity3d - Player ReSpawn Logic Unity 多人游戏
- css - 以 2 种颜色为边框的按钮
- java - instagram 或直接如何在图标启动器中不改变形状以在 android oreo 中圈出
- reactjs - 如何从 MaterialUI 抽屉中删除边距/填充?
- floating-point - Determining decimal precision of a floating point number
- c++ - 头文件的使用