我正在制作科学记谱法,所以让我给你看一下代码:
import time
def scientific_notation(number):
decimal = ""
for thing in str(number):
"""
Loops through the number to add stuff to "decimal"
(probably not necessary but i'm going to keep it
there in case I need a filter.)
"""
if len(decimal) == len(str(number)):
break
else:
decimal += thing
decimal = decimal.replace('0','')
print(decimal)
while float(decimal) > 10:
# Uses decimal notation
actual = ''
# To keep track of the original place
for x in range(0,len(str(number))):
actual += str(number)[x]
decimal = decimal.replace(str(number)[x],str(number)[x]+'.')
# Adding decimal points to each place until the float version of that is less than 10
if decimal.count('.') > 1:
# if there's more than one decimal, replace that value with what it was before
decimal = decimal.replace(str(number)[x],actual)
elif float(decimal) > 10:
# if the float version of the decimal is more than 10, wait for the while loop to realize that by doing nothing
pass
else:
pass
else:
# Output
power = '10^'+str(str(number).count('0'))
print(decimal+" * "+power)
scientific_notation(102)
好吧,既然你已经看了它,那就让我告诉你发生了什么。
因此,在while循环中,我的if语句不执行
if decimal.count('.') > 1
或者至少,没有正确执行,导致
ValueError: could not convert string to float: '1.102.'
因为我的while循环尝试将其转换为浮点数,但得到的是' 1.102。'并引发ValueError,因为您无法将带有两个小数点的内容转换为float。关于为什么if语句不起作用的任何想法?我不知道,也许我只是愚蠢。
答案 0 :(得分:2)
Eek你的代码是可怕的,并立即做了一些意想不到的事情。例如:
decimal = ""
for thing in str(number):
"""
Loops through the number to add stuff to "decimal"
(probably not necessary but i'm going to keep it
there in case I need a filter.)
"""
if len(decimal) == len(str(number)):
break
else:
decimal += thing
与
相同decimal = str(number)
也
decimal = decimal.replace('0','')
这会将102
变为12
,而这不是故意的。
让我们看一个不同的算法,并用算术而不是字符串操作来处理它。
def scientific_notation(number):
n = 0
while number > 10:
n += 1
number /= 10
print(f"{number} * 10^{n}")
>>> scientific_notation(102)
1.02 * 10^2