Java方法的定义和调用

题目描述

定义一个名字为f的方法,它根据参数的值x将下面分段函数对应的函数值返回回来。

x的取值范围                           f(x)的值
x < -13                              4.8x+10
-13≤x<0                          30/x^(x立方分之30)
0≤x≤10                                  x
x>10                                  2.5x-48

在主方法main中重复20次(读入x的值,以它实参去掉用上述方法,并将方法调用的返回值输出出来,输出时保留2位小时,每次输出时要求换行)。

程序代码

import java.text.DecimalFormat;
import java.util.Scanner;

public class Main {
    
    

    static double f(double x) {
    
    
        if (x < -13) {
    
      //   x < -13
            x = 4.8 * x + 10;   // 4.8x+10
        } else if (-13 <= x && x < 0) {
    
      // 	-13≤x<0
            x = 30 / (x * x * x);  //  30/x^(x立方分之30)
        } else if (0 <= x && x <= 10) {
    
      // 0≤x≤10
                   // x
        } else if (x > 10) {
    
      // 	x>10
            x = 2.5 * x - 48;  // 2.5x-48
        }
        return x;
    }

    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        for (int i = 0; i < 20; i++) {
    
       // 重复20次
            double num = scanner.nextDouble();   // 键盘输入 num
            DecimalFormat df = new DecimalFormat("#0.00");
            System.out.println(df.format(f(num)));  // 将结果格式化保留2位小数
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44989881/article/details/112381495