实验2-2-4 计算分段函数[2] (10 分)
本题目要求计算下列分段函数f(x)
的值:
f
(
x
)
=
{
x
0.5
x>=0
(
x
+
1
)
2
+
2
x
+
1
/
x
x<0
f(x)=\begin{cases} x^{0.5}& \text{x>=0}\\ (x+1)^{2}+2x+1/x& \text{x<0} \end{cases}
f(x)={x0.5(x+1)2+2x+1/xx>=0x<0
注:可在头文件中包含math.h
,并调用sqrt
函数求平方根,调用pow
函数求幂。
输入格式:
输入在一行中给出实数x。
输出格式:
在一行中按“f(x) = result”
的格式输出,其中x与result都保留两位小数。
输入样例1:
10
输出样例1:
f(10.00) = 3.16
输入样例2:
0.5
输出样例2:
f(-0.50) = -2.75
代码:
# include <stdio.h>
# include <stdlib.h>
# include <math.h>
int main(){
double x,result;
scanf("%lf",&x);
if (x >= 0) result = sqrt(x);
else result = pow(x+1,2) + 2 * x + 1.0 / x;
printf("f(%.2lf) = %.2lf",x,result);
return 0;
}
提交截图:
解题思路:
主要是math.h
库的使用,导入这个库可以使用一些封装好的现成的数学公式,常见的sqrt
、pow
等等