C 中的变量乘法?
//Hydroelectric Dam Helper
#include <stdio.h>
#define GRAV 9.80
#define EFINC 0.9
#define EFINC2 90
int main()
{
//Defines all the variables to be used
double height, work, mass;
printf("Height of dam (in meters):");
scanf("%lf", &height);
printf("Flow of water (in thousand cubic meters per second):");
scanf("%lf", &mass);
work = (mass * GRAV * height * EFINC);
printf("The dam would produce %f megawatts at %d%% efficency", &work, EFINC2);
return 0;
}
值设置正确,我通过打印高度和质量来测试它,但工作从未收到值,并且 EFINC2 打印出一个我不太确定的荒谬数字
//Hydroelectric Dam Helper
#include <stdio.h>
#define GRAV 9.80
#define EFINC 0.9
#define EFINC2 90
int main()
{
//Defines all the variables to be used
double height, work, mass;
printf("Height of dam (in meters):");
scanf("%lf", &height);
printf("Flow of water (in thousand cubic meters per second):");
scanf("%lf", &mass);
work = (mass * GRAV * height * EFINC);
printf("The dam would produce %f megawatts at %d%% efficency", &work, EFINC2);
return 0;
}
The values set correctly, I tested it by having it print height and mass but work never receives a value, and EFINC2 prints out a ridiculous number that I'm not really sure about
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
应该是:
&work
是一个指向 work 的指针,即double*
但要让printf
打印需要传递 < 的值code>double 而不是指针。在您的平台上,double*
的大小可能与double
不同,导致后续的printf
格式使用错误的数据。should read:
&work
is a pointer to work, i.e. adouble*
but forprintf
to print the value you need to pass adouble
and not a pointer. On your platform adouble*
is probably a different size to adouble
causing the subsequentprintf
formats to use the wrong data.问题是您让 printf 输出带有
%f
说明符的float
,但通过&work 传入
。只需删除double*
&
即可正常工作。The problem is that you are having printf output a
float
with the%f
specifier but passing in adouble*
via&work
. Just remove the&
and it should work fine.您收到“荒谬的数字”的原因是您将
work
的地址传递给printf()
。将&work
更改为work
它应该可以正常工作。The reason why you are receiving a "ridiculous number" is that you are passing the address of
work
toprintf()
. Change&work
towork
and it should work properly.当然。 printf 行中的与号
&
表示读取变量work
的地址,而不是读取值 >Sure. The ampersand
&
in the printf-line means that the address of the variablework
is read instead of the value尝试将 ad 附加到常量以强制 c 不强制转换为 int 可能会起作用。您还可以尝试将值显式转换为 float 或 double。
Try appending a d to the constants to force c to not cast to int might work. You could also try explicitly casting the values to either float or double.
您已经给出了 &work ,它是工作变量在内存中的地址,因此它不会打印任何荒谬的值,它会打印工作的内存位置。
您应该删除 &从 &work 接收 work 变量的值。
printf("大坝将以 %d%% 效率生产 %f 兆瓦", work, EFINC2);
you have given &work which is the address of work variable in memory, so it doesn't print any absurd value, it prints the memory location of work.
You should remove & from &work to receive value of work variable.
printf("The dam would produce %f megawatts at %d%% efficency", work, EFINC2);