[英]why is the output of my program 0.000000 when it should be the value i entered when prompted. below is the code
我正在尝试执行此代码。 但是数字变量没有存储我输入的值,这可能是对这种行为的可能解释。
#include <stdio.h>
int main(){
float number;
printf("enter a value\n");
scanf("%5.3f",&number);
printf("u entered : %f",number);
return 0;
}
以下是其执行示例
enter a value
78.467
u entered : 0.000000
为什么数字不存储值 78.467
%5.3f
不是有效的scanf
格式。 它应该是%f
。scanf
是否成功。 总是做。例子:
#include <stdio.h>
int main() {
float number;
puts("enter a value");
if(scanf("%f", &number) == 1) { // check that it succeeds
printf("u entered : %5.3f", number); // in printf %5.3f is ok
} else {
puts("Erroneous input");
}
}
"%5.3f"
in scanf("%5.3f",&number);
是无效格式,因此结果是未定义的行为 (UB)。
"5"
没问题。 它将转换中读取的字符数限制为最多 5 个。
".3"
不是有效转换规范的一部分。
节省时间,启用所有警告。 @大卫·拉涅利
// scanf("%5.3f",&number);
if (scanf("%f",&number) != 1) {
fprintf(stderr, "Non-numeric input\n");
return -1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.