输入一个整数,若为奇数则输出其平方根,否则输出其立方根java
时间: 2024-05-19 07:17:21 浏览: 15
抱歉,我可以回答这个问题。下面是Java代码实现:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = input.nextInt();
if (num % 2 == 1) {
System.out.println(Math.sqrt(num));
} else {
System.out.println(Math.cbrt(num));
}
}
}
当输入一个整数时,程序会判断该数是奇数还是偶数,如果是奇数则输出其平方根,否则输出其立方根。
相关问题
输入一个整数,若为偶数,输出其平方根,否则输出其立方根,代码
当输入一个整数时,可以使用以下代码实现判断并输出平方根或立方根的功能:
```python
import math
def calculate_root(num):
if num % 2 == 0:
result = math.sqrt(num)
else:
result = math.pow(num, 1/3)
return result
# 示例输入为整数10
input_num = 10
output = calculate_root(input_num)
print(output)
```
上述代码中,我们首先导入了math模块,以便使用平方根和立方根的计算函数。然后定义了一个名为`calculate_root`的函数,该函数接受一个整数作为参数。在函数内部,我们使用条件语句判断输入的整数是否为偶数,如果是偶数,则调用`math.sqrt()`函数计算平方根;如果是奇数,则调用`math.pow()`函数计算立方根。最后,将计算结果返回。
示例中的输入为整数10,根据题目要求,10是偶数,因此输出为10的平方根,即3.1622776601683795。
输入一个整数,若为奇数则输出其平方根,否则输出其立方根。要求分别用单分支、双分支及条件运算实现java
单分支实现:
```
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);
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)