我儿子正试图制作一个计算器来帮助他完成许多页的家庭作业。我知道简单的解决方案是告诉他wolfram alpha,但我认为这可能是一个有趣的项目。我需要一些关于如何迭代其余数字并以分步格式打印解决方案的帮助。这就是他目前所拥有的:
# Variables
X = input("input the first number with space between digits: ")
Y = int(input("input the second number: "))
Xn = X.split(" ")
if int(Xn[0]) >= Y: # if Y fits in X the do a simple division and return the remainder
Xy1 = int(Xn[0])
fit0 = int(Xy1 / Y)
rem0 = Xy1 - fit0 * Y
print(" It fits " + str(fit0), "times ", " the remainder is: " + str(rem0))
else: # if Y does not fit in X the add the first two strings of X and convert them to integers then do a simple
# division and return the remainder
Xy0 = (int(Xn[0] + Xn[1]))
fit = int(Xy0 / Y)
rem = Xy0 - fit * Y
print(" It fits " + str(fit), "times ", " the remainder is: " + str(rem))
这里,我做了一个逐步打印除法的例子。
我对x(被除数用空格分隔(和除数进行了硬编码。您只需将其更改为包含来自用户的输入即可
x = "1 4 8 7"
divisor = 5
# convert x to a list of integers
x = [int(i) for i in x.split(" ")]
dividend = x[0]
i = 0 # index of the current dividend digit
quotient = ""
while i < len(x)-1:
i += 1
quotient += str(dividend // divisor)
remainder = dividend % divisor
print(f"{dividend} / {divisor} -> {dividend // divisor} (remainder {remainder})")
dividend = remainder * 10 + x[i]
quotient += str(dividend // divisor)
remainder = dividend % divisor
print(f"{dividend} / {divisor} -> {dividend // divisor} (remainder {remainder})")
print(f"Result: {quotient} (remainder {remainder})")
结果是:
1 / 5 -> 0 (remainder 1)
14 / 5 -> 2 (remainder 4)
48 / 5 -> 9 (remainder 3)
37 / 5 -> 7 (remainder 2)
Result: 297 (remainder 2)
我想我误解了这个问题。。。为什么不使用float?
x = float(input("input the first number: "))
y = float(input("input the second number: "))
print(f" It fits {x//y} times , the remainder is: {x/y-x//y}")