Per*_*man -2 c floating-point printf
我有一些非常简单的代码,我遇到了问题.这个程序只是计算一个人的体重(千克)并显示它.但是,每次运行时,打印的答案都会返回0.00000,但会返回正确的答案.有人看到我的代码有什么问题吗?
#include <stdio.h>
#include <math.h>
int main(void)
{
float w;
float const wc=0.454;
printf("Enter your weight in pounds ");
scanf("%f", &w);
float wk = w * wc;
printf("Your weight in kilograms is: %f", &wk);
return(wk);
}
Run Code Online (Sandbox Code Playgroud)
您不需要将变量的地址作为格式说明符的参数传递以打印该值.你需要改变
printf("Your weight in kilograms is: %f", &wk);
Run Code Online (Sandbox Code Playgroud)
至
printf("Your weight in kilograms is: %f", wk);
Run Code Online (Sandbox Code Playgroud)
那说,
始终检查返回值scanf().不这样做,万一scanf("%f", &w);失败了,你就可以调用未定义的行为,你会最终使用未初始化的局部变量float wk = w * wc;中float wk = w * wc;.
请不要return看起来像一个功能.尽量坚持下去return wk;.