Calculating nth root in Java using power method

后端 未结 9 2676
礼貌的吻别
礼貌的吻别 2021-02-18 22:08

I was trying to get a cubic root in java using Math.pow(n, 1.0/3) but because it divides doubles, it doesn\'t return the exact answer. For example, with 125, this g

9条回答
  •  失恋的感觉
    2021-02-18 22:24

    Well this is a good option to choose in this situation. You can rely on this-

       System.out.println("     ");
       System.out.println("     Enter a base and then nth root");
       while(true)
       {
           a=Double.parseDouble(br.readLine());
           b=Double.parseDouble(br.readLine());
           double negodd=-(Math.pow((Math.abs(a)),(1.0/b)));
           double poseve=Math.pow(a,(1.0/b));
           double posodd=Math.pow(a,(1.0/b));
           if(a<0 && b%2==0)
           {
               String io="\u03AF";
               double negeve=Math.pow((Math.abs(a)),(1.0/b));
               System.out.println("     Root is imaginary and value= "+negeve+" "+io);
           }
           else if(a<0 && b%2==1)
           System.out.println("     Value= "+negodd);
           else if(a>0 && b%2==0)
           System.out.println("     Value= "+poseve);
           else if(a>0 && b%2==1)
           System.out.println("     Value= "+posodd);
           System.out.println("     ");
           System.out.print("     Enter '0' to come back or press any number to continue- ");
           con=Integer.parseInt(br.readLine());
           if(con==0)
           break;
           else
           {
               System.out.println("     Enter a base and then nth root");
               continue;
           }
        }
    

提交回复
热议问题