这个用c语音该怎么写,初学者写不出

img


救命救命呐,这个用c语音写分段函数该怎么写,写了很多遍一直报错,看不懂……

if判断计算就好了呀

#include <stdio.h>
#include <math.h>
int main()
{
    double x,y;
    scanf("%lf",&x);
    if(x>=0)
       y = sqrt(x);
    else
       y = pow((x+1),2)+ 2*x +1/x;
    printf("f(%.2lf) = %.2lf",x,y);
}
 

#include <stdio.h>
#include <math.h>
int main()
{
    double x,y;
    scanf("%lf",&x);
    if(x>=0)
       y = sqrt(x);
    else
       y = (x+1)*(x+1) + 2*x + 1/x;
    printf("f(%.2lf) = %.2lf",x,y);
}

分段函数,考察的是if...else...结构。

#include<stdio.h>
#include<math.h>
int main (void)
{
    double x,y;
    scanf("%lf",&x);
    if (x>=0) {
        y=sqrt(x);
    }
    else {
        y=pow(x+1,2)+2*x+1/x;
    }
    printf("f(%.2f) = %.2f",x,y);
    return 0;
}

供参考:

#include <stdio.h>
#include <math.h>
int main()
{
    double x, result;
    scanf("%lf", &x);
    if (x < 0)
        result = pow(x+1,2) + 2 * x + 1.0 / x;
    else
        result = sqrt(x);
    printf("f(%.2f) = %.2f", x, result);
    return 0;
}