#include <stdio.h>
#include <math.h>
#define G 9.81
typedef struct
{
double weight;
double drag;
double time;
} USER_INPUT;
double calculateVelocity(USER_INPUT);
int main(int argc, char **argv)
{
USER_INPUT userInput;
double velocity;
printf("Please enter weight, drag and time: ");
scanf("%lf %lf %lf", &userInput.weight, &userInput.drag, &userInput.time);
velocity = calculateVelocity(userInput);
printf("At t = %f , the parachutist with weight %d kg\nand a drag coefficient %8.2f kg/s \n will have a velocity of %8.2f m/s^2", &userInput.time, &userInput.weight, &userInput.drag, velocity);
return 0;
}
double calculateVelocity(USER_INPUT data)
{
double velocity;
// TODO compute velocity
return velocity;
}
在主函数中,我想显示结果。
如何打印结构中定义的变量?
我尝试了 %f
,它返回 0.000000,而 %d
返回一个随机数。
最佳答案
你在打印时犯了错误,
请注意'&'用于获取任何变量的地址,而不是值。所以当你打印时:
printf("At t = %f , the parachutist with weight %d kg\nand a drag coefficient %8.2f kg/s \n will have a velocity of %8.2f m/s^2", &userInput.time, &userInput.weight, &userInput.drag, velocity);
你实际上是在打印变量的地址:
&userInput.time((userInput.time)的地址), &userInput.weight((userInput.weight) 的地址), &userInput.drag((userInput.drag) 的地址).
您想打印它们的值,而不是地址,因此在打印时删除“&”:
即;
printf("At t = %f , the parachutist with weight %d kg\nand a drag coefficient %8.2f kg/s \n will have a velocity of %8.2f m/s^2", userInput.time, userInput.weight, userInput.drag, velocity);
关于c - 如何在结构中打印变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41994266/