Java中将两个整数转换为双精度

问题描述

这是任务:

在类“ Functionality.java”中实现名为“ createDouble”的静态公共方法。该方法获取两个整数值a和b作为输入,并应将它们转换为双精度值并按如下所示返回它:

  • 第一个输入值a应该放在逗号或点之前。
  • 第二个输入值b应该在逗号或点后,并且多余的零应被删除。

不能使用任何导入来解决此任务。此外,禁止使用数学库或其他库。实现一种至少包含一个有意义的循环的算法。

这是我的主意

public class Functionality {

    public static double createDouble(int a,int b) {
        double c = b;
        double d = 1;
        while (c >= 1) {
            c /= 10;
            d *= 10;
        }
        return a + b/d;
    }

    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE);
        System.out.println(createDouble(12,Integer.MAX_VALUE));
    }
}

问题是我正在使用不应使用的方法Integer.MAX值。还有另一种编写此代码的选项吗?

解决方法

您的代码看起来不错,我只需要短短的一周时间。变量document.getElementById("rm" + i).addEventListener("click",(e) => { // etc. 在完成除法后将等于您想要的c,因此您可以直接使用它。否则,您根本不需要使用b。只需使用任意值即可。

Integer.MAX_VALUE

输出:

public class Functionality
{
  public static double createDouble(int a,int b) {
    double c = b;
    while(c >= 1)
      c /= 10;
    return a + c;
  }
  
  public static void main(String[] args) {
    System.out.println(createDouble(15,351));
    System.out.println(createDouble(32,8452));
  }
}
,

这是我的实现

public class Functionality {
    private static double logb10(double num){
        return (num > 1) ? 1 + logb10(num / 10) : 0;
    }
    public static double createOtherDouble(int a,int b) {
        double c = a;
        int len =(int) logb10(b);
        double d = b;
        for(int i = 0; i < len; i++){
            d /= 10;
        }
        return c + d;
    }
     public static void main(String []args){
        System.out.println(Integer.MAX_VALUE);
        System.out.println(createOtherDouble(12,Integer.MAX_VALUE));
     }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...