如何对平方根使用变量?

时间:2018-09-19 18:36:31

标签: python math.sqrt

所以,我加入只是为了做到这一点。如何使用变量求平方根?

这是代码。

    ##Algebra 2 Radicals Calculator
import math

input("Before we start, put frations in parentheses. It should look like (3/5). Press any key to continue.")

a = input("If the base is just x, type 1. If the base has a number and a variable, type 2. If the base has just a number, type 3. ")
if a == "1":
    x = input("What is the base? ")
    y = input("What is the Exponent's Numerator? ")
    z = input("What is the Exponent's Denominator? ")
    print(y,"√",x,"^",z)

if a == "2":
    b = input("What is the number in the base? ")
    e = input("What is the variable? ")
    c = input("What is the Exponent's Numerator? ")
    d = input(" What is the Exponent's Denominator? ")
    X = sqrt(b)
    if b == (X).is_integer():
        print(X, c,"√",e,"^",c)
    elif b != (X).is_integer():
        print(c,"√",b,e,"^",d)

1 个答案:

答案 0 :(得分:1)

首先,input()返回字符串,而不是数字,但是math.sqrt()要求其参数为数字。因此,您需要这样做:

b = float(input("What is the number in the base? "))

,并且对于所有其他输入类似(如果输入应为不带小数部分的数字(例如小数的分子和分母),请使用int()代替float())。

然后要计算平方根,您需要调用math.sqrt(),而不仅仅是sqrt()

X = math.sqrt(b)

然后您的if语句是错误的。

if b == (X).is_integer():

is_integer()方法返回TrueFalse,但是b是用户输入的数字,而不是真值。如果要确定b是否等于X的整数部分,则应为:

if int(b) == int(X):

elif测试应该只是else:,因为它只是测试相反的条件。