本学期开始上Python课程,我遇到了当前任务的麻烦。通过现在在课堂上完成的例子和练习,找不到任何东西。
Q1)已修复
aN = raw_input("Enter a number with decimals")
bN = raw_input("Enter a binary number, 2 to 4 digits in length")
if (bN[-1] == 1):
print "The binary number was odd so your number will contain 2 decimals"
print "The number is now",aN[0:4],
elif (bN[-1] == 0):
print "The binary number was even so your number will contain 1 decimal"
print "The number is now",bN[0:3]
我希望它能够打印出两个语句,每个结果一个。如果输入的二进制数以“1”结尾,则会以2位小数形式输出aN,如果输入的二进制数以“0”结尾,则会以1位小数吐出aN。
运行时,在显示用户为bN
输入的值后,它不会执行任何操作Q2)有没有更好的方法在小数点后找到数字?切片仅在数字< 10。
编辑)对那个指出弦乐的人来说,我完全忘记了:(
aN = raw_input("Enter a number with decimals")
bN = raw_input("Enter a binary number, 2 to 4 digits in length")
if (float(bN[-1]) == 1):
print "The binary number was odd so your number will contain 2 decimals"
print "The number is now",aN[0:4],
elif (float(bN[-1]) == 0):
print "The binary number was even so your number will contain 1 decimal"
print "The number is now",aN[0:3]
如果有人能回答第二个问题,那就太棒了。
答案 0 :(得分:0)
raw_input()
将输入作为字符串。在if
条件下,您正在使用整数来编写字符串。让你的if
像这样,
if float(bN[-1]) == 1:
print "The binary number was odd so your number will contain 2 decimals"
print "The number is now %.2f" % float(aN)
elif float(bN[-1]) == 0:
print "The binary number was even so your number will contain 1 decimal"
print "The number is now", bN[0:3]
如果要在小数点后打印2位数,可以按照这种方法进行操作。
答案 1 :(得分:0)
首先,raw_input()
将输入视为str
。
因此,aN[-1]
与int
的任何比较都会产生False
。即您的代码将始终运行else
块。
此外,您需要首先找到小数点的索引,然后计算是否显示一个或两个位置(或处理没有小数点的情况)
aN = raw_input("Enter a number with decimals")
bN = raw_input("Enter a binary number, 2 to 4 digits in length")
if (bN[-1] == '1'):
print "The binary number was odd so your number will contain 2 decimals"
if aN.find('.') == -1:
print "The number is now ",aN
else:
print "The number is now ", aN[:aN.find('.')+3]
elif (bN[-1] == '0'):
print "The binary number was even so your number will contain 1 decimal"
if aN.find('.') == -1:
print "The number is now ",aN
else:
print "The number is now ", aN[:aN.find('.')+2]
答案 2 :(得分:0)
假设aN总是至少有1个小数,这应该是有效的。您可以使用find()
找到“。”小数点。
aN = raw_input("Enter a number with decimals")
bN = raw_input("Enter a binary number, 2 to 4 digits in length")
if (bN[-1] == "1"):
print "The binary number was odd so your number will contain 2 decimals"
print "The number is now", aN[:aN.find(".")+3]
elif (bN[-1] == "0"):
print "The binary number was even so your number will contain 1 decimal"
print "The number is now", aN[:aN.find(".")+2]
示例:
>>> aN
'1.12345'
>>> bN
'11'
>>> if (bN[-1] == "1"):
... print "The binary number was odd so your number will contain 2 decimals"
... print "The number is now", aN[:aN.find(".")+3]
... elif (bN[-1] == "0"):
... print "The binary number was even so your number will contain 1 decimal"
... print "The number is now", aN[:aN.find(".")+2]
...
The binary number was odd so your number will contain 2 decimals
The number is now 1.12