从键盘读取任意一个非0正整数x,判断这个数是否是平方数,如果是,则输出这个数的平方根,如果不是,则输出0。
时间: 2024-05-10 18:20:45 浏览: 58
```python
import math
x = int(input("请输入一个非0正整数:"))
if math.sqrt(x) == int(math.sqrt(x)):
print("这个数的平方根为:", int(math.sqrt(x)))
else:
print(0)
```
思路解析:
1. 首先从键盘读取一个非0正整数x,使用 `input()` 函数读取用户输入的字符串,再使用 `int()` 函数将字符串转换为整数类型。
2. 使用 `math.sqrt()` 函数计算x的平方根,如果平方根为整数,则说明x是平方数,否则不是平方数。
3. 判断是否为平方数,如果是,则输出这个数的平方根,使用 `int()` 函数将平方根转换为整数类型;如果不是,则输出0。
注意:需要先导入 `math` 模块才能使用 `math.sqrt()` 函数。
相关问题
编写程序,从键盘读取任意一个非0正整数x,判断这个数是否是平方数,如果是,则输出这个数的平方根,如果不是,则输出0
```python
import math
x = int(input("请输入一个非0正整数:"))
if x > 0 and math.isqrt(x) ** 2 == x:
print(math.isqrt(x))
else:
print(0)
```
注:`math.isqrt()` 是 Python 3.8 引入的新函数,用于求整数的平方根。如果使用的是较早的 Python 版本,可以使用 `int(math.sqrt(x))` 来代替。
编写c语言代码,从键盘读取任意一个非0正整数x,判断这个数是否是平方数,如果是,则输出这个数的平方根,如果不是,则输出0。
```c
#include <stdio.h>
#include <math.h>
int main() {
int x;
printf("请输入一个非0正整数:");
scanf("%d", &x);
if (x <= 0) { // 判断输入是否是非0正整数
printf("输入错误!\n");
return 0;
}
int s = sqrt(x); // 计算平方根
if (s * s == x) { // 判断是否是平方数
printf("%d的平方根为%d\n", x, s);
} else {
printf("0\n");
}
return 0;
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![torrent](https://img-home.csdnimg.cn/images/20250102104920.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)