c - 如何在结构中打印变量?

标签 c struct printf

#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/

相关文章:

c - 为什么系统之间打印的位数不同?

c - C中的变量地址

c - [NSDictionary getObjects :andKeys:] 示例

c - 数据类型 : symbol vs enumerated?

c# - C++ CLI 结构到字节数组

c - 指向结构的指针

c - 错误: Void Value not ignored as it ought to be, C 编程

c - 为什么有时不需要在 C 中分配内存?

c - 了解包含反斜杠 (\012) 的 printf 输出

c - 程序在每次输入后打印一个值为 10 的额外行