Reputation: 15
The program compiles but when running it I am not getting the correct values back from my inputs. I have looked for a way to make the sine formula and have found this one but I don't believe it was right.
Is my formula correct? I think just running the sin
function in C is giving me the wrong value as well.
Update: I'm still getting the wrong values with these changes if I input 1.5 and 4. I'm getting 0.000 and a random integer
/*
* Function mySin is using a sin formula to get the sin of x
* the function then returns the sin value computed
* Parameters -for function mySin are "x" is the value for sin
* -"n"is the number of series to run
*
*The program also uses the sin(x) function to get the 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 and n:");
scanf("%lf",&x);
scanf("%d",&n);
mySin(x,n);
realSin=sin(x);
printf("mySin= %f\n sin=%d\n",sinx,realSin);
}
Upvotes: 0
Views: 2966
Reputation: 1498
mySin
should return double
. You are returning int
.
sin
values can be calculated with the Fourier series.
Upvotes: 1
Reputation: 41805
One more incorrect point in your code is that you're calculating power by **
There's no power operator in C. The compiler is treating x**i
as x * (*i)
. But since i
is not a pointer, it returns the error you saw. You must use pow()
instead
Upvotes: 1
Reputation: 280857
Your mySin
function is wrong in at least 5 separate ways. Using **
to represent exponentiation (to avoid confusion with xor), the correct formula is
sin(x) = x - x**3/3! + x**5/5! - x**7/7! + x**9/9! ...
Your implementation fails because
Furthermore, main
is wrong in several more ways. The return value of mySin
is completely ignored. Instead, sinx
is the first argument to main
, which is the number of command-line arguments the program received (including the name it was run as). Also, %d
is used for all numbers in format strings, regardless of type, when it's only meant for int
.
To fix mySin
, have i
only go over odd values, and have every iteration of the loop compute x**i/i!
and add it into the current value of sinx
.
To fix main
, declare a local sinx
variable in main
and assign sinx = mySin(x, n)
instead of declaring sinx
as an argument. Also, use %lf
for reading doubles with scanf
and %f
for writing doubles with printf
.
Upvotes: 5
Reputation: 1687
x is double so you have to use the %lf in scanf and %f in the printf
double x;
scanf("%lf", &x);
printf ("%f", x);
Upvotes: 1