简体   繁体   English

尝试通过C中的运动学创建垂直运动

[英]Attempting to create vertical motion via kinematics in C

I'm attempting to print the height y as a function of time t. 我正在尝试将高度y打印为时间t的函数。

EDIT: Alright I got the code to work now, thanks to all of you! 编辑:好的,感谢大家,我现在可以使用代码了! I appreciate your help! 我感谢您的帮助!

 #include <stdio.h>

 int main() {
    double t, g = -9.8, v = 20;
    double y;

    for(t = 0; t < 4.079; t = t + .02){
        y = (( v * t) + ( .5 * g * t * t ));
        printf("value of y: %f\n", y);
    }
    return 0;
}

On this line: 在这行上:

printf("value of y: %d\n", y);

%d is for printing integers ( int ). %d用于打印整数int )。

You are trying to print a double . 您正在尝试打印double

Use %f to print a double . 使用%f打印一个double


You will have to re-calculate the value of y every time in your loop: 每次循环时,您都必须重新计算y的值:

for(t = 0; t < 4.079; t = t + .02) {
    y = ((v * t) + (.5 * g * ( t * t));
    printf("value of y: %d\n", y);
}

pow becomes a reserved word/syntax once you use math.h and compile with the -lm flag linking that math library. 一旦使用math.h并使用链接该数学库的-lm标志进行编译, pow将成为保留的字/语法。 pow is then a function from math.h so you cannot use pow as a variable where you do double pow(double t, double s); pow是math.h中的函数,因此您不能将pow用作执行double pow(double t, double s);的变量double pow(double t, double s);

It is best, if not just for human readability, to simply declare all your variables first. 最好,不仅是为了便于阅读,最好先声明所有变量。 Then at most, when declaring them, assign them a value like you do for g and v . 然后最多在声明它们时,像为gv一样为它们分配一个值。

Consider this modification to your code: 考虑对代码的此修改:

# include <stdio.h>
# include <math.h>

int main ( void )
{
   const double gravity = -9.8;   /* don't be afraid to use full words */
   double v = 20;
   double t, s;
   double p;   /* changed from pow */
   double y;

   p =  pow( t, s );    /* this is t^s consider using a better variable name than the letter p */

   /* for equations like this `y=` below,                          */
   /* putting the textbook definition of it just prior and         */
   /* and explaining what you are trying to do will help immensely */
   /* later on when your program gives the wrong answer and you    */
   /* are scratching your head trying to figure out why            */
   /* and especially if it is someone else                         */


   y = (v * t) + (0.5 * gravity * pow(t, 2.0) );

   for ( t = 0; t < 4.079; t = t + .02)
   {
      printf("value of whatever: %lf\n", whatever );   /* original code had %d here, must use %lf because your variables are type double */
   }

   return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM