简体   繁体   English

返回函数时显示sqrt

[英]Displaying sqrt when returning a function

I am just learning to code so i decided to make a project for myself making a function that finds the zero of a parabola. 我只是在学习编码,所以我决定为自己创建一个项目,创建一个找到抛物线零的函数。 I think the issue i am having is actually printing out the sqrt . 我认为我遇到的问题实际上是在打印sqrt

This is the error I receive: 这是我收到的错误:

File "C:/Users/someb/AppData/Local/Programs/Python/Python37-32/Quadratic Formula Solver revised.py", line 10, in find_zero
    return float(-b) + "+-" + float(math.sqrt(discriminant)) + "/" + float(2 * a)
TypeError: unsupported operand type(s) for +: 'float' and 'str'

This is my like fifth revision of the code trying different ways, this originally was supposed to display the two different answers. 这是我的第五次尝试不同方式的代码修订版,本来应该显示两个不同的答案。

#Real Zero Finder QUadratic Formula
import math
def find_zero(a,b,c):
    discriminant = (b ** 2 - 4 * a * c)
    if discriminant < 0 :
        return "No real Zeros"
    elif discriminant == 0 :
        return "Vertex is the Zero"
    else:
        #This is where the error is taking place
        return float(-b) + "+-" + float(math.sqrt(discriminant)) + "/" + float(2 * a)

def disc(a,b,c):
    return math.sqrt(b ** 2 - 4 * a * c)

You're getting this error because Python doesn't know how to add a string to a float. 您收到此错误是因为Python不知道如何向浮点数添加字符串。 You know you're trying to do concatenate the float to the string, but Python doesn't. 您知道您正在尝试将浮点数连接到字符串,但是Python没有。

The simplest way to print multiple things in Python 3.6+ is to use formatted string literals (f-strings): https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings You put a f before your string and then put what you want to appear in the string inside curly braces { } . 在Python 3.6及更高版本中打印多种内容的最简单方法是使用格式化的字符串文字(f-strings): https : //docs.python.org/3.6/reference/lexical_analysis.html#f-stringsf放在字符串,然后将要显示的内容放在花括号{ }

return f'{-b} +- {math.sqrt(discriminant)} / {2 * a}'

As mentioned above, you can't add strings and floats. 如上所述,您不能添加字符串和浮点数。 Since you appear to be outputing a message, I'd prefer to fix this by converting the floats to strings, then the '+' will concatenate those strings. 由于您似乎正在输出一条消息,因此我更愿意通过将浮点数转换为字符串来解决此问题,然后“ +”将连接这些字符串。 This returns a single string, which may be more useful that returning several values. 这将返回一个字符串,这可能比返回多个值更有用。

return str(-b) + " +- " + str(math.sqrt(discriminant)) + " / " + str(2 * a)

I also scrapped the float() conversions... I don't think they do anything here. 我还取消了float()转换...我认为它们在这里没有做任何事情。

Problem is here in return: 问题在这里作为回报:

return float(-b) + "+-" + float(math.sqrt(discriminant)) + "/" + float(2 * a)

you're trying to connect float to a String , instead of plus, use commas: 您尝试将float连接到String ,而不是加号,请使用逗号:

return float(-b), " +- ", float(math.sqrt(discriminant)), " / ", float(2 * a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM