ValueError: Could not convert string to a float: ' '

ValueError: Could not convert string to a float: ' '

我陷入了一个非常混乱的问题。我尝试从客户端向套接字发送三个整数来求解二次方程。但是我尝试了两种方法,它总是给我一个错误:ValueError:无法将字符串转换为浮点数:''。请帮我解决这个问题。非常感谢大家。

#Client side
import socket
import sys
HOST, PORT = "127.0.0.1", 50000
while 1 :
    # data = " ".join(sys.argv[1: ]) 
    '''
    data1 = input('Enter a : ')
    data2 = input('Enter b: ')
    data3 = input('Enter c: ')
    '''
    data = input('Enter a, b, c respectively: ')

    # create a socket ()
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock :
        #
        sock.connect((HOST, PORT))
        #sock.send(str.encode("\n".join([data1, data2, data3])))
        sock.send(str(data).encode())
        #
        received = sock.recv(1024)

        received = received.decode('utf-8')
        received = eval(received)
        #print('Sent: ', data1, ' ', data2, ' ', data3)
        print('Sent: ', data)
        print('Received: ', received)
        break
# Server side
from encodings import utf_8
import math
from socket import socket, AF_INET, SOCK_STREAM

from sympy import re
BUFFER_SIZE = 1024
s = socket(AF_INET, SOCK_STREAM)
s.bind(("", 50000))
s.listen(5)
print('Server is listening...')
conn, addr = s.accept()

def GiaiPhuongTrinhBac2(a, b, c) :
    lst = []
    if a == 0 :
        if b == 0 :
            if c == 0 :
                return lst.append('Phương trình vô số nghiệm!')
            else : 
                return lst.append('Phương trình vô nghiệm!')
        else :
            x = -(c / b)
            return lst.append(x)
    else :
        delta = b * b - 4 * a * c
        if delta == 0 :
            return lst.append( (-b) / (2 * a) ) 
        elif delta > 0 :
            x1 = (-b - math.sqrt(delta)) / (2 * a)
            x2 = (-b + math.sqrt(delta)) / (2 * a)
            lst.append(x1)
            lst.append(x2)
        else :
            lst.append('Phương trình vô nghiệm!')

while 1 :
    '''
    received = conn.recv(BUFFER_SIZE).decode('utf-8').split("\n")

    data1 = float(received[0])
    data2 = float(received[1])
    data3 = float(received[2])

    if not (data1 and data2 and data3) :
        break
    print('Received data: ', data1, data2, data3)
    '''
    received = conn.recv(BUFFER_SIZE).decode('utf-8').strip().split(" ")
    print(received)
    data1 = float(received[0])
    data2 = float(received[1])
    data3 = float(received[2])

    lst =[]
    lst = GiaiPhuongTrinhBac2(data1, data2, data3)
    '''
    lst = []
    lst.append(received)
    '''
    conn.send(str(lst).encode())

conn.close()

我尝试输入a,b,c的字符串用' '和'\n'分割,但好像不成功。

发送后,接收到的数据被刷新。所以下一轮在while循环中收到的变量数据为null。 所以你,不要使用 while 循环或将这些行移到 while 循环中:

while True:
   s.listen(5)
   conn, addr = s.accept()

并且在您的代码中还有更多问题,例如您无法在 return 中追加。正确解法:

lst.append('Phương trình vô số nghiệm!')
return lst