gpt4 book ai didi

python - 从文件读取、存储值和数学运算

转载 作者:行者123 更新时间:2023-11-30 23:49:04 27 4
gpt4 key购买 nike

我正在尝试从包含城市名称、里程表读数以及剩余燃油量的文件中读取内容。文本文件的内容是:

Kennewick 97840.4 40.0<br>
Benton_City 97861.3 37.6<br>
Prosser 97878.2 35.9<br>
Grandview 97886.5 35.0<br>
Sunnyside 97894.6 34.1<br>
Granger 97904.6 33.1<br>
Toppenish 97913.0 32.2<br>
Wapato 97921.7 31.3<br>
Union_Gap 97931.6 30.4<br>
Yakima 97935.2 30.0<br>
Selah 97939.4 29.6<br>
Ellensburg 97972.7 26.0<br>
Thorp 97981.1 25.1<br>
Rosyln 98002.8 22.6<br>
Easton 98016.1 21.1<br>
North_Bend 98058.1 16.9<br>
Preston 98067.7 16.0<br>
Issaquah 98073.6 15.4<br>
East_Gate 98082.9 14.4<br>
Mercer_Island 98088.5 13.7<br>
Seattle 98095.4 13.0<br>

赋值的一部分是从上次读取中减去当前读取(这两个值都存储在变量英里中)。

def BusRoute():
path = "C:\\"
ext = ".txt"

lines = ""
stopname = ""
miles = 0
prevmiles = 0
milest = 0
fuel = 0.0
mpg = 0.0
i = 0

filename = input("Please enter the file name. The file path [C:\...] and extension [*.txt] is not required: ")

inFile = open(path + filename + ext, "r")

for lines in inFile:
stopname, miles, fuel = lines.split(" ")

miles = float(miles)
fuel = float(fuel)

prevmiles = miles

milest = miles - prevmiles

miles += 1

print("Since last stop:", float(milest), "miles")

我的问题是,我试图将上次读取的 miles 值存储在名为 prevmiles 的变量中,然后减去 prevmiles (最后读取的里程)是从当前的英里读数中得出的,但它不断地从当前的英里中减去当前的英里,显然使得该值我想打印出 0.0。

最佳答案

你有

prevmiles = miles

milest = miles - prevmiles

这保证了 Milet 将为 0。尝试交换这两行的顺序。

关于python - 从文件读取、存储值和数学运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7797174/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com