(OJ)Java基础-设计分段函数

设计分段函数

Problem Description

已知函数:
	(1) x>0,y=x+3; 
	(2) x=0,y=0; 
	(3) x<0,y=x2-1,
请设计一个方程序实现上面的函数,根据传入的值x的不同,返回对应的y值xxxxxxxxxx1 1请编写程序,计算“1+3+5+7+...+N”的值

Input Description

输入一个数值,然后回车

Output Description

输出计算后的数值

Sample Input

32

Sample Output

35

解题代码

import java.util.Scanner;

public class Main{
    
    

    public static void main(String[] args) {
    
    
        // 创建scanner对象
        Scanner in = new Scanner(System.in);
        // 接受输入的x
        int x = in.nextInt();
        // 结果变量 如果x=0 y=0
        int res = 0;
        // 如果x > 0 y = x + 3
        if (x > 0 ) res = x + 3;
        // x < 0 y = x^2 - 1 
        else if(x < 0) res = x * x -1;
        // 最近C/C++的代码写的有点多 这个if-else if没有加括号
        System.out.println(res);
        // 关闭scanner 输入流
        in.close();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40856560/article/details/112523929