参数之间的对应关系是怎样的?

问题遇到的现象和发生背景

在做练习时遇到的关于参数的问题

用代码块功能插入代码,请勿粘贴截图

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLOutput;
import java.text.NumberFormat;
@Controller
public class CalController {
    String[] cal0(double yr,int m,double p){//抽取if中的方法
        double mr = yr / 12 / 100.0;
        double pow = Math.pow(1 + mr, m);
        double payment = p * mr * pow / (pow - 1);

        return new String[]{
                NumberFormat.getCurrencyInstance().format(payment * m),
                NumberFormat.getCurrencyInstance().format(payment * m - p)
        };
    }
    @RequestMapping("/cal")
    @ResponseBody
    String[] cal(double p, int m, double yr,int type) {
        double mr = yr / 12 / 100.0;//在cal方法中有效
        if(type == 0){
            return cal0(p,yr,m);

        } else {//等额本金
            double payPrincipal = p / m; //每月偿还的本金
            double payInteresttol=0;
            double backcup = p;
            for(int i=0;idouble payInterest = p * mr;//每月偿还利息
                p -= payPrincipal;  //每月剩余本金
                payInteresttol += payInterest;//还款总利息
            }
            //[0]还款总额 [1]还款总利息
            return new String[]{
                    NumberFormat.getCurrencyInstance().format(backcup+payInteresttol),
                    NumberFormat.getCurrencyInstance().format(payInteresttol)
            };
        }

    }
运行结果及报错内容

在代码if中调用cal0方法时,”return cal0(p,yr,m);”语句中的yr会报错,显示“需要的类型int,
提供的类型double”,而在我按照idea提示“重新排列实参”之后,将参数排序修改为(yr,m,p)之后报错就消失了

我的解答思路和尝试过的方法

在猜测是参数排序和参数类型的问题,经过排列组合之后发现只有第二个参数是m时不会报错,第二参数放yr
或者p都会报”需要的类型int,提供的类型double“,我又将cal方法中的参数m的类型修改为double,此时(yr,m,p)
中的参数m也开始报错了。

int 赋值给 double 类型 ,范围扩大, 隐式转换允许

img

double 赋值给 int 类型,范围缩小,隐式转换不允许

img

double 赋值给 int 类型,需要显示转换,即强转

img


如有帮助,欢迎采纳哈!

在这里插入图片描述

本人的开源项目,欢迎star支持下!!!