作者:墨启飞
环境:c++(vs2019) java(IDEA 2021)
时间:2021.10.5
题目 1007: [编程入门]分段函数求值
时间限制: 1Sec 内存限制: 128MB 提交: 53667 解决: 29817
题目描述
有一个函数
y={ x x<1
| 2x-1 1<=x<10
{ 3x-11 x>=10
写一段程序,输入x,输出y
输入
一个数x
输出
一个数y
样例输入复制
14
样例输出复制
31
错误代码:#include
using namespace std;
int main()
{
int X,y;
cin>>x;
if(x<1){
cout<<"y="<
if(1<=x<10){
cout<<"y="<<2x-1<
if(x>=10){
cout<<"y="<<3x-11<
return 0;
}
bug:没分清楚题目的大意,应用到If-else语句,还要注意输出格式(
输入
一个数x
输出
一个数y)
调试成功代码:
#include
using namespace std;
int main()
{
int x;
cin >> x;
if(x<1)
{
cout << x;
}
else if(1<=x && x<10)
{
cout << 2*x-1;
}
else
{
cout << 3*x-11;
}
return 0;
}
java 版:
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) {
- // if else
- Scanner sc = new Scanner(System.in);
- int x = sc.nextInt();
- int y=0;
- if (x < 1) {
- y = x;
- } else if (x >= 1 && x < 10) {
- y = 2 * x - 1;
- } else if (x >= 10) {
- y = 3 * x - 11;
- }
- System.out.println(y);
- }
- }



