What is wrong with my calculations of sinx & cosx? The formula to calculate the two was given and I believe I have written the code correctly, however when the program runs, it simply displays the value entered in. (exp.) I enter in 5, program runs, displays 5 as my sinx. What have I done wrong here?
//
// Take Home Test #1
// 9-27-13
// Library includes
#include <stdio.h>
#include <math.h>
//Main entry point
int main(void){
//Variable declaration
float valuex = 0.0;
float sinx = 0.0;
float cosx = 0.0;
//Displaying a message to the user
printf("Approximation of sin^2(x)+cos^2(x):\n");
//Read in a float value from the user
printf("Please enter a value between 0 and 5: ");
scanf("%f", &valuex);
//Making sure the value is within defined range
if (valuex >= 0 && valuex <= 5 ){
sinx = valuex - 1/6*(valuex*valuex*valuex) + 1/120*(valuex*valuex*valuex*valuex*valuex);
printf("sin(x) = %f.\n", sinx);
cosx = 1 - 1/2*(valuex*valuex) + 1/24*(valuex*valuex*valuex*valuex);
printf("cos(x) = %f.\n", cosx);
} elseif (valuex < 0 ){
printf("Please enter a valid value.\n");
} elseif (valuex > 5 ){
printf("Please enter a valid value.\n");
}
//Calculating and displaying the approximation of sin^2(x)+cos^2(x)
//sinx = valuex - 1/6*(valuex*valuex*valuex) + 1/120*(valuex*valuex*valuex*valuex*valuex);
//printf("sin(x) = %f.\n", sinx);
//cosx = 1 - 1/2*(valuex*valuex) + 1/24*(valuex*valuex*valuex*valuex);
//printf("cos(x) = %f.\n", cosx);
//valuex - 1/6*(valuex*valuex*valuex) + 1/120*(valuex*valuex*valuex*valuex*valuex)
}
This worked! Thanks you so much! Would you mind explaining my mistake more thoroughly? Why does simply placing 1/6 or 1/24 as a fractional multiplier not work?
You should try a simple code example for yourself, to see how integer division works.
There are two important things, anything after the decimal point is discarded, so that 22/7 gives exactly 3 rather than 3.14285 and 1/2 gives exactly 0 instead of 0.5
The other point is that any literals such as 22 or 3.14 are considered by the compiler to be of a particular type such as int, float, double and so on. If there is no decimal point, the value is an integer. With a decimal point, such as 22.0 or 1.0, the value is of type double
You can further specify the type with a subscript letter such as f for float. (note that floats are less precise than doubles)