[英]why is the output of my program 0.000000 when it should be the value i entered when prompted. below is the code
I am trying to execute this code.我正在尝试执行此代码。 but the number variable isn't storing the value I input,what could be posssible explanations of this behaviour.但是数字变量没有存储我输入的值,这可能是对这种行为的可能解释。
#include <stdio.h>
int main(){
float number;
printf("enter a value\n");
scanf("%5.3f",&number);
printf("u entered : %f",number);
return 0;
}
and below is sample of its execution以下是其执行示例
enter a value
78.467
u entered : 0.000000
Why isn't number storing the value 78.467为什么数字不存储值 78.467
%5.3f
is not a valid scanf
format. %5.3f
不是有效的scanf
格式。 It should be %f
.它应该是%f
。scanf
succeeds.您也不会检查scanf
是否成功。 Always do.总是做。Example:例子:
#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);
"%5.3f"
in scanf("%5.3f",&number);
is an invalid format so the result is undefined behavior (UB).是无效格式,因此结果是未定义的行为 (UB)。
The "5"
is OK. "5"
没问题。 It limits the number of characters read in the conversion to at most 5.它将转换中读取的字符数限制为最多 5 个。
".3"
is not part of a valid conversion specification. ".3"
不是有效转换规范的一部分。
Save time, enable all warnings.节省时间,启用所有警告。 @David Ranieri @大卫·拉涅利
// 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.