m.s - 4 years ago 115

C Question

I know java and now I am trying to learn C. I have a math problem and I tried to do it on C but I think I don't know if this part of my code is correct or not. The math exercise is

- If
**|x|>1**then**f(x)=1.0 ÷ √(|x² − 1.0|)**. - If
**|x|=1**then it would be**f(x)=0**. - Last case: if
**|x|<1**then**f(x)=1.0 ÷ √(|1.0-x²|)**.

Here is my code:

`for (x = a; x <= b; x = x + h) {`

while (x < b) {

if (abs(x) > 1) {

y = 1 / sqrt(pow(x, 2) - 1);

printf("y= %d", y);

} else

if (abs(x) == 1) {

y = -9999;

printf("y= %d", y);

} else

if (abs(x) < 1) {

y = 1 / sqrt(1 - pow(x, 2));

printf("y= %d", y);

}

}

}

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Your code has an infinite loop: the `while`

condition is constant as `x`

is not modified in its body. This `while`

loop is actually redundant and should be removed.

You should move the code into a function definition and give the argument and return values the type `double`

:

```
double f(double x) {
if (fabs(x) > 1.0) {
return 1.0 / sqrt(x * x - 1.0);
} else
if (fabs(x) == 1) {
return 0.0;
} else {
return 1.0 / sqrt(1.0 - x * x);
}
}
```

Use it in this loop:

```
void print_values(double a, double b, double h) {
for (double x = a; x <= b; x = x + h) {
printf("f(%g) = %g\n", x, f(x));
}
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**