Problem1036--分段函数

1036: 分段函数

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 52  Solved: 38
[Submit] [Status] [Web Board] [Creator:]

Description

描述

编写程序,计算下列分段函数y=f(x)的值。

y=-x+2.5; 0 <= x < 5

y=2-1.5(x-3)(x-3); 5 <= x < 10

y=x/2-1.5; 10 <= x < 20


Input

一个浮点数N,0 <= N < 20

Output

输出N对应的分段函数值:f(N)。结果保留到小数点后三位。

Sample Input

1.0

Sample Output

1.500

HINT

多种方法实现:
第一种 省略了else的if语句写法
#include <iostream>
using namespace std;
int main()
{
 double x,y;
 cin>>x;
 if(x<5&&x>=0) y=-x+2.5;
 if(x<10&&x>=5) y=2-1.5*(x-3)*(x-3);
 if(x<20&&x>=10) y=x/2-1.5;
 
 printf("%.3lf",y);
 return 0;
}


第二种:在else语句内嵌套了if   else
#include <iostream>
using namespace std;
int main()
{
 double x,y;
 cin>>x;
 if(x<0||x>=20) {
  cout<<"输入不正确"; return 0;
 }
 else if(x<5) y=-x+2.5;
     else if(x<10)
      y=2-1.5*(x-3)*(x-3);
       else if(x<20) y=x/2-1.5;
 
 printf("%.3lf",y);
 return 0;
}


第3种 在if里面嵌套了if else
#include <iostream>
using namespace std;
int main()
{
 double x,y;
 cin>>x;
 if(x<20&&x>=0)
   if(x<5) y=-x+2.5;
     else if(x<10)
      y=2-1.5*(x-3)*(x-3);
       else  y=x/2-1.5;
  
  else
  {
  cout<<"输入不正确"; return 0; }
 printf("%.3lf",y);
 return 0;
}


练习:


苹果50斤以下2.5一斤,超过50斤,100以下 2.4一斤 ,100以上的就2.2 用3种结构实现一个程序

Source/Category


[Submit] [Status]