输入一个整数,若为奇数则输出其平方根,否则输出其立方根。要求分别用单分支、双分支及条件运算实现java
时间: 2024-04-29 14:26:46 浏览: 96
单分支实现:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
if (num % 2 == 1) {
System.out.println(Math.sqrt(num));
} else {
System.out.println(Math.cbrt(num));
}
}
}
```
双分支实现:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
if (num % 2 == 1) {
System.out.println(Math.sqrt(num));
} else if (num % 2 == 0) {
System.out.println(Math.cbrt(num));
}
}
}
```
条件运算实现:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
String result = (num % 2 == 1) ? String.valueOf(Math.sqrt(num)) : String.valueOf(Math.cbrt(num));
System.out.println(result);
}
}
```
阅读全文