函数 getInput 有什么问题?

what is wrong with function getInput?

程序未完成,不知道为什么,重量,阻力和时间变量中没有存储值(内部结构USER_INPUT),如果我打印重量,阻力和时间,它们是0。 我还没有开始编写程序的其余部分,我是否在主要功能中犯了一些错误?

#include  <stdio.h>

#define G 9.8
#define index 3

typedef struct
{
double weight;
double drag;
double time;
}USER_INPUT;

double velocities[index];

double getInput(USER_INPUT);
double calculateVelocities(USER_INPUT);

void main(void)
{
double velocity;
USER_INPUT input;

getInput(input);
calculateVelocities(input);



printf("Velocities for the parachuties with weight %f\n", input.weight);
printf("and a drag coefficient %f\n", input.drag);

printf("\n\n    Time     Velocities m/s\n");
printf("---------------------------------\n");
printf("        %f       %f\n", input.time, velocities[0]);
printf("        %f       %f\n", input.time, velocities[1]);
printf("        %f       %f\n", input.time, velocities[2]);




}

double getInput(USER_INPUT input)
{
printf("Please enter weight, drag and time:\n");
scanf("%lf %lf %lf", &input.weight, &input.drag, &input.time);

printf("%f  %f  %f\n"), input.weight, input.drag, input.time;
}

double calculateVelocities(USER_INPUT input)
{
velocities[0]=1;
velocities[1]=2;
velocities[2]=3;

}

这有几个不同的问题。

  1. 这是getInput下的错字:

    printf("%f  %f  %f\n"), input.weight, input.drag, input.time;
    

    应该是这样的:

    printf("%f  %f  %f\n", input.weight, input.drag, input.time);
    
  2. 您的函数 getInputgetVelocities 应该 return void 而不是 double。 改变这个:

    double getInput(USER_INPUT);
    double calculateVelocities(USER_INPUT);
    

    至此

    void getInput(USER_INPUT);
    void calculateVelocities(USER_INPUT);
    

    然后对定义做同样的事情。

  3. 您通过 value 而不是指针将 USER_INPUT 传递给您的函数。如果要设置 struct 的字段,则将其作为指针传递,然后在函数中取消引用一次。按值传递意味着接收对象的函数实际上只是将对象内容复制到一个新对象中。所以引用 &input.width 是引用复制对象上的 width 字段,而不是 main 函数中的原始字段。

    例如,您的 getInput 函数应该是:

    // declaration
    void getInput(USER_INPUT*);
    
    // stuff
    
    // definition
    void getInput(USER_INPUT *input)
    {
      printf("Please enter weight, drag and time:\n");
      scanf("%lf %lf %lf", &((*input).weight), &((*input).drag), &((*input).time));
    
      printf("%f  %f  %f\n", input->weight, input->drag, input->time);
    }
    

    多余的括号是为了让大家一目了然。但是您可以更简单地将 &((*input).weight) 写为 &(input->weight).

    然后你必须用你的 calculateVelocities 函数做同样的事情。

    最后,要调用那些新定义的函数,请执行以下操作:

    getInput(&input);