# Thread: Help why this program stacking...

1. ## Help why this program stacking...

Hi there,

It is my mid-term exam and I need it today, does anybody knows, why my program get stack?

Here is the code:

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

main(void)
{

double x, n, sine, terms;
int i;
double pi = 3.14159265;

scanf("%f", &x);

x = x*pi/180.0;

sine = x;
terms = x;

for (i=1; terms<0.00001; i++)
{
terms = (-1)*terms*x*x/(2*i*(2*i+1));
sine = sine + terms;
}

printf("\n\n\n");
printf("The value of the sine is %f to %d terms.\n\n",sine,i);

getch ();
}

2. And by "stack" you mean what?

3. It's dinner time and I need my food, and I need it now!

4. Code:
`scanf("%f", &x);`
While you can use the specifiers for float and double interchangeably with printf, you can't with scanf. That should be %lf since x is a double.

sine = sine + terms; would be better as sine += terms;

main is an integer type, it should be int main(void), not main(void). This means it needs a return statement too, stick return 0; at the end.

If you're going to do arithmetic with different data types, you kind of need to change them all to one type...
terms = terms*x*x/(double)(-2*i*(2*i+1)); // get rid of the -1 in front and just change 2 to -2
...
terms *= x*x/(double)(-2*i*(2*i+1)); // even better

5. When I compiled it, it comes with no error..then, when I run it, the Message "Please enter the value of (x) in radians: " comes out and when I enter a value, it get "stuck"...sorry for that...

6. In other words, the solution doesn't converge.

terms<0.00001 should really be fabs(terms) < 0.00001, since terms can be positive or negative, that's probably the problem right there.

7. Many thanks to you Epy...it fixed my problem, just I need to submit it as it is...

Am not that good in math, but I have to submit what I understood and I can explain...

8. The question of my instructor is Loop until it becomes small than 10-5...any other idea you can share?

9. Originally Posted by arnobie
The question of my instructor is Loop until it becomes small than 10-5...any other idea you can share?
terms<0.00001 should really be fabs(terms) < 0.00001, since terms can be positive or negative, that's probably the problem right there.
Btw, you'll need math.h for fabs.

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

int main(void)
{

double x, sine, terms;
int i;
double pi = 3.14159265;

printf("Please enter the value of (x): ");
scanf("%lf", &x);

x = x*pi/180.0;

sine = x;
terms = x;

for (i=1; fabs(terms)<0.00001; i++)
{
terms = terms*x*x/(double)(-2*i*(2*i+1));
sine += terms;
}

printf("\n\n\n");
printf("The value of the sine is %lf to %d terms.\n\n",sine,i);

getch ();
return 0;
}

11. Originally Posted by arnobie

12. Originally Posted by bithub