简体   繁体   中英

Square root in Java

Am I supposed to write in Java like that? If not, how should I write it?

在此输入图像描述

import java.util.*;
public class Soru {
    public static void main(String[] args) {    
        int m,n,c;
        double f=0;
        Scanner type = new Scanner(System.in);
        System.out.print("Enter the m value :");
        m=type.nextInt();
        System.out.print("Enter the n value :");
        n=type.nextInt();
        System.out.print("Enter the c value :");
        c=type.nextInt();       
        f=Math.pow(c, m/n);
        System.out.println("Resul:"+f);
    }
}

Like with other langauges, m/n will be an integer, and for m=1,n=2 , you will get m/n=0

Consider making m and n as doubles - or cast them to it in the evaluation, if you want a non integer result.

Example:

int m = 1, n = 2, c = 9;
System.out.println(Math.pow(c, m/n));
System.out.println(Math.pow(c, ((double)m)/n));

Will yield:

1.0
3.0

Though your logic is correct and will work perfectly if m/n is an int there are cases where it will fail to give the correct result. For example, 5^(5/2) will give the result of 5^2 . So make the following changes:

int m,n,c;
double f=0;
Scanner type = new Scanner(System.in);
System.out.print("Enter the m value :");
m=type.nextInt();
System.out.print("Enter the n value :");
n=type.nextInt();
System.out.print("Enter the c value :");
c=type.nextInt();
f=Math.pow(c, (double)m/n);
System.out.println("Resul:"+f);

Full code as follows:

import java.util.*;

public class Soru {

    public static void main(String[] args) {
        int m,n,c;
        double f=0;
        Scanner type = new Scanner(System.in);
        System.out.print("Enter the m value :");
        m=type.nextInt();
        System.out.print("Enter the n value :");
        n=type.nextInt();
        System.out.print("Enter the c value :");
        c=type.nextInt();
        f=Math.pow(c, (double)m/n);
        System.out.println("Resul:"+f);    
    }
}

Output

Enter the m value :5
Enter the n value :2
Enter the c value :2
Resul:5.65685424949238

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM