function - creating a Sin formula in c programming -
the program compile when running not getting correct values inputs, had looked way make sine formula , had found 1 don't believe right.
is formula correct? think running sin function in c giving me wrong value well.
* still getting wrong values these changes if input 1.5 , 4 im getting 0.000 , random integer
/* * function mysin using sin formula sin of x * function returns sin value computed * parameters -for function mysin "x" value sin * -"n"is number of series run * *the program uses sin(x) function real sin * */ #include <stdio.h> #include <math.h> int mysin(double x, int n){ int i=0; double sinx=0; for(i=1; i<=n; i+=2){ sinx=(pow(x,i)+sinx); // } return sinx; } int main(double sinx){ double realsin=0; double x=0; int n=0; printf("please input x , n:"); scanf("%lf",&x); scanf("%d",&n); mysin(x,n); realsin=sin(x); printf("mysin= %f\n sin=%d\n",sinx,realsin); }
your mysin
function wrong in @ least 5 separate ways. using **
represent exponentiation (to avoid confusion xor), correct formula is
sin(x) = x - x**3/3! + x**5/5! - x**7/7! + x**9/9! ...
your implementation fails because
- it discards previous terms on every iteration of loop.
- it doesn't alternate signs.
- it includes even-exponent terms.
- it doesn't compute factorial in divisor.
- the return type int, discarding fractional component of computed result.
furthermore, main
wrong in several more ways. return value of mysin
ignored. instead, sinx
first argument main
, number of command-line arguments program received (including name run as). also, %d
used numbers in format strings, regardless of type, when it's meant int
.
to fix mysin
, have i
go on odd values, , have every iteration of loop compute x**i/i!
, add current value of sinx
.
to fix main
, declare local sinx
variable in main
, assign sinx = mysin(x, n)
instead of declaring sinx
argument. also, use %lf
reading doubles scanf
, %f
writing doubles printf
.
Comments
Post a Comment