sin(x) = x - x3/3! + x5/5! - x7/7!.... c programming

Thread Starter

Kudzie06

Joined Feb 8, 2010
3
can anyone give me a clue On this C programming solution. I am not getting an out put.


sin(x) = x - x3/3! + x5/5! - x7/7!....

#include <stdio.h>
#include <math.h>
//#include "stdafx.h"

int factorial (int);


int main ()
{
int n, m;
float x,sinx;
printf("input a value for x :");
scanf_s("%f",&x);
//comp_op=sin((double)x);
//printf("computer value: %f",comp_op);


n=1;
sinx=0;
while (n<=4);
{
n =pow(-1,(n-1)*pow(x,(2*(n-1)+1))/factorial(2*(n-1)+1));
sinx +=n;
}
printf("sin%f=%f",x, sin(x));
//scanf_s("%f",&x); return 0;
}
int factorial(int n);

int factorial(int n)
{







int factorial=1;
while(n>0)
{
factorial*=n;
n--;
}
return factorial;
}

Thank you
 

rjenkins

Joined Nov 6, 2005
1,013
I'd do it incrementally at each stage, eg.

x^3 to x^5 to x^7; at each stage multiply by x squared (which you pre-calculate).

3! to 5! to 7!; at each stage multiply by two steps of an encrementing sequence, like
f *= fact++; From 3! to 5! it would start at 4, so you do *4 then *5.
f *= fact++;

Next loop, you would get *6 then *7 to go from 5! to 7!

I assume you are doing this as an excercise rather than calculating a sine for use in a program?
 

Ele

Joined Mar 6, 2010
9
//Just modified your code a bit, try this and see what happens, just
// set the + or - for your 3^ 5^ or 7^: 'Clean up the code after you see
//what happens, or you see where it went wrong for you'

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

using namespace std;

int factorial(int a);
int n,b;
int lngFract[20];
int main(){

system("PAUSE");

int m,i,j;
float z,y,x,sinx;
printf("input a value for x :");
scanf("%f",&x);
printf("d= %f",x);

system("PAUSE");

b=1;
n=1;
j=3;
m=2;
i=1;
sinx=0;

while (i<5){
if (i == 1)
sinx = sinx + x;
else
{
z = pow(x,m + 1);
//printf("x= %f",z);
n = factorial(j);
//printf("n= %d",n);
y = z/n;
//printf("y= %f",y);
m = m + 2;
j = j + 2;
sinx = sinx + y;
//printf("sin%f=%f",x, sin(x));
}
++i;
}
printf("sin%f=%f",x, sin(x));
system("PAUSE");
return EXIT_SUCCESS;
//scanf_s("%f",&x); return 0;
}

int factorial(int a)
{
//printf("d= %d",n);
if (b==1)
{
n =a;
lngFract[b-1] = a;
b++;
}
else
{
lngFract[b-1] = a;
n = lngFract[b-1] * n;
//printf("d= %d",n);
b++;
}
if (a > 1)
{
factorial (a-1);
}
b=1;
return n;
}
 
Top