如何在python中将50显示为5√2的平方根

贾斯基拉特·辛格·马斯金

我正在编写一个程序来在 python 中输出一个数字的平方根。我当前的代码如下所示:

import math
num = int(input("Enter the number for which you want the square root"))

if math.floor(math.sqrt(num)) == math.ceil(math.sqrt(num)):
    v = math.sqrt(num)
    print(f"The given number is perfect square and the square root is {v} ")
elif num <0:
    print("The square root of the given number is imaginary")
else:
    print(f"The square root of the given number is \u221A{num}") 
    #\u221A is unicode for square root symbol

我当前的程序检查输入的数字是否是完全平方,然后显示平方根。如果它不是一个完美的正方形,它只显示√num。例如,如果 num 为 300,它将显示 √300。但我希望它显示为 10√3。关于我如何做到这一点的任何想法。我不希望结果中有任何小数。

阿兰·T。

您可以找到作为您的数字的除数的最大根,并将余数表示为 √xxx 部分:

def root(N):
    for r in range(int(N**0.5)+1,1,-1):
        if N % (r*r) == 0:
            n = N // (r*r)
            return str(r) + f"√{n}"*(n>1)
    return f"√{N}"
        
print(root(50)) # 5√2
print(root(81)) # 9
print(root(96)) # 4√6
print(root(97)) # √97

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章