用数学技巧判断一个数是否是一个完美的正方形

2024-06-16 13:35:21 发布

您现在位置:Python中文网/ 问答频道 /正文

第一个岗位在这里

我想知道输入的数字是不是一个完美的正方形。这就是我想到的(我完全是个初来乍到的笨蛋)

import math

num = int(input("enter the number:"))

square_root = math.sqrt(num)
perfect_square = list[1, 4, 5, 6, 9, 00]
ldigit = num%10

if ldigit in perfect_square:
     print(num, "Is perfect square")

列表是数字,如果整数以结束,它将是一个完美的正方形。你知道吗

perfect_square = list[1, 4, 5, 6, 9, 00]

TypeError: 'type' object is not subscriptable

从没见过这个(惊喜)。抱歉,如果这是一个完全混乱的逻辑和理解。你知道吗


Tags: theimportinput数字mathnumlistint
3条回答

您的代码中有一个错误:

perfect_square = list[1, 4, 5, 6, 9, 00]

应该是:

perfect_square = ['1', '4', '5', '6', '9', '00']

其次,它们被定义为int,因此不能有数字00,而是将所有内容转换为字符串进行检查,然后使用strint返回int。你知道吗

就我个人而言,我宁愿采用另一种方法:

import math

num = int(15)
square_root = math.sqrt(num)

if square_root == int(square_root):
    print(f"{num} is a perfect square")
else:
    print(f"{num} is not a perfect square")

声明一个没有关键字“list”的列表,如下所示:

perfect_square = [1, 4, 5, 6, 9, 00]

在python中创建list对象不需要list关键字。你知道吗

List是python内置类型。列表文字写在方括号[]中。你知道吗

例如: 正方形=[1,4,9,16]

方格在这里是一个列表。你知道吗

阿什图什

相关问题 更多 >