# Using C to Solve Problems

This is a discussion on Using C to Solve Problems within the C Programming forums, part of the General Programming Boards category; For the function , what are the roots? Write a program that determines the roots by looking for values of ...

1. ## Using C to Solve Problems

For the function , what are the roots? Write a program that determines the roots by looking for values of x in the range [-5, 5] for which the function has a value of zero.

additional requirements:
1) Make the variables fx and x of type double.

2) When iterating through values of x, increment x in steps of 0.001.

3) The expression for representing f(x) should not use any math library functions. You can represent this expression, including the powers, with the four basic math operations.

4) When calculating floating point values, it is not unusual for the answers to not be exact. In this program, we would like to find the values of x that make fx = 0, but it's possible that the value of fx will not be exactly 0. Therefore, we will compare the magnitude of fx to a very small number. To get the absolute value of a floating point number, the math library includes the function fabs(). Here is how to use it.

if(fabs(fx) < 0.000000001)
do something;

5) When printing the results, for fx show 15 decimal places and for x show 3 decimal places.

I am stuck on what to new next.

Code:
```#include <stdio.h>

int main (void)
{
double fx, x;

fx = x*x*x + 2*x*x - 5*x - 6;```

2. well, to start you out an easy one would be this:
Code:
```double my_pow(double num, int expon)
{
int i;
double retval;

retval = num;
expon--;
for (i = 0; i < expon; i++){
retval *= num;
}
return retval;
}```
I completed my documentation project today. . . I'm in a giving mood.

3. Originally Posted by Kennedy
I completed my documentation project today. . . I'm in a giving mood.

Here's "save an operation":

Code:
``` /*expon--;    let's not.... */
for (i = 1; i < expon; i++){
retval *= num;
}```

4. HA,brezeale CSE 1310 at UTA LOL!!!!

Here is the code!!
Code:
```#include <stdio.h>
#include<math.h>

int main (void)
{
double x, fx;
for(x = -5.0; x <=5.0; x+= .001)
{
fx = (x*x*x) + (2*x*x) - (5*x) - 6;
if(fabs(fx) < 0.000000001)
printf("fx is %.15f, x is %.3f\n",fx,x);

}

}```

5. I would suggest finding the result of the function that's closest to zero.... as opposed to settling on something possibly too early. The function may have multiple near-zeros, or none at all. Keep a running "closest-so-far" value.

6. Code:
```double x , a , b;

x = 16.0 // the number to find the square root of

a = 1.0;
b = 0.0;
while(a != b){
b = x/a;
a = (a + b)/2.0;
}```

Popular pages Recent additions