This is my code for attempting a while
Loop to model a pendulum swing, however the values produced don't seem to help me:
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
main()
{
float theta = 0; // initial value for angle
float omega = 0.2; // initial value for angular speed
float time = 0; // initial time
float dt = 0.01; // time step
while (theta < 2 * PI && -2*PI) {
time = time + dt;
theta = theta + omega*dt;
printf("theta=%i, omega=%i, time=%i, and dt=%i\n", theta, omega, time, dt);
}
system("PAUSE");
}
How can I modify this to be more helpful? The while condition I have to use is that it should stop when the pendulum has made one revelation either forwards or backwards (-2PI or 2PI). I need to use the formula 'omega=omega-(g/l)dtsin(theta)' and NOT make the assumption that theta approximately equals sin(theta).
while(theta <2*PI&&-2*PI)
In c
if we want to combine multiple expressions we can combine them using logical operators as
while((theta < 2 * PI) && (theta > -2 * PI))
PS- I am no physics expert. Change conditions as per your requirement
There are some problem in this code :
According to the standard you shouldn't use
main()
But either
int main()
int main(void)
int main(int argc, char *argv[])
Also don't forget
return 0;
Sample program :
#include <stdio.h>
int main(void) {
/* Do stuff */
return 0;
}
If you wish to read more information about that, click here.
As LutzL pointed out you should use M_PI
instead of your definition of PI. Just #include <math.h>
That's how you would print the value for example :
printf("\nValue of M_PI is %f\n\n", M_PI);
Read more here.
As pointed out by rootkea :
In c if we want to combine multiple expressions we can combine them using logical operators as
while((theta < 2 * PI) && (theta > -2 * PI))
If you want greater precision (I think that this is the case) you should use double
instead of float
.
You are trying to print float
variables with the "%i"
format specifier. That's wrong, "%i"
is used to print int
signed integer and using the wrong specifier invokes undefined behavior. You should use "%f"
to print float or double signed decimal.
Have a read about printf format specifiers here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With