【问题标题】:How to display square root if 50 as 5√2 in python如何在python中将50显示为5√2的平方根
【发布时间】:2021-10-28 21:36:21
【问题描述】:

我正在编写一个程序来在 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。关于我如何做到这一点的任何想法。我不希望我的结果中有任何小数。

【问题讨论】:

  • 将数字拆分为其质因数并在其中找到相等的数字对!顺便说一句,这是一个软件开发社区,而不是数学社区。​​span>

标签: python square-root


【解决方案1】:

您可以找到作为您的数除数的最大根,并将余数表示为 √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

【讨论】:

    【解决方案2】:

    你可以使用sympy:

    import sympy
    sympy.init_printing(use_unicode=True)
    sympy.sqrt(300)
    

    输出:

    10√3
    

    【讨论】:

      猜你喜欢
      • 2011-05-15
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多