在方法重载中传递不同数据类型的值 [英] Passing values of different data types in Method Overloading

查看:57
本文介绍了在方法重载中传递不同数据类型的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我向正在重载的方法传递了一个双精度值,但它把它当作浮点数并调用查找正方形面积的方法.浮点值的末尾应该有一个f"才能被认为是浮点数,对吗?那么为什么我的程序在应该调用圆的面积"时调用浮动正方形的面积"呢?

I pass a double value to the method that is being overloaded but it takes it as float and invokes the method for finding area of square. Float values should have an "f" to their end to be considered float right? so why does my program invoke float 'area of square' when it's supposed to invoke 'area of circle'?

public class App {
    public void calArea(float a) {
        System.out.println("Area of square is Side x Side : " + a * a);
    }

    public void calArea(float a, float b) {
        System.out.println("Area of rectangle is length x width" + a * b);
    }

    public void calArea(double r) {
        double area = (Math.PI * r * r);
        System.out.println("Area of circle is Radius x Radius x PI : " + area);
    }

    public static void main(String[] args) {

        App app = new App();

        app.calArea(5);
    }

}

推荐答案

我只是将我的评论作为答案发布,因为这是无需强制转换即可解决问题的唯一方法.

I just post my comment as an answer, because it is the only way to resolve your problem without casting.

而不是使用doublefloat 来区分应该计算哪些区域.只需以不同的方式命名它们.当看到你的代码时,这将消除很多头痛.

Instead of using double and float to distinguish what areas should be calculated. Just name them differently. This will remove a lot of headache when seeing your code.

app.calArea(5) 会计算圆形或正方形的面积吗?

Will app.calArea(5) calculate the area of a circle or a square?

所以只需将您的代码更改为:

So just change your code to this:

public class App {
    public void calAreaSquare(double a) {
        System.out.println("Area of square is Side x Side : " + a * a);
    }

    public void calAreaRectangle(double a, double b) {
        System.out.println("Area of rectangle is length x width" + a * b);
    }

    public void calAreaCircle(double r) {
        double area = (Math.PI * r * r);
        System.out.println("Area of circle is Radius x Radius x PI : " + area);
    }

    public static void main(String[] args) {

        App app = new App();

        app.calAreaCircle(5);
    }
}

我还建议只使用 double,以提高精度.

I would also suggest just using double only, for the enhanced precision.

这篇关于在方法重载中传递不同数据类型的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆