到目前为止我有这个但是我在下面逐字看到了溢出错误。它似乎不喜欢prod = num_1 + num_ 2行,因为这是触发错误的原因。
def p_mult(num_1, num_2):
prod = 0
while num_2 != 0:
if (num_1%2 != 0): # is odd?
num_1 = (num_1-1) / 2
num_2 = (2 * num_2) + num_2
prod = num_1 * num_2
elif (num_1%2 == 0): # is even?
num_1 = num_1 / 2
num_2 = 2 * num_2
prod = num_1 * num_2
return prod
当我尝试我的模块时它在解释器中说明:... p_mult(3,38)
OverflowError:int太大而无法转换为float
我应该设计一个农民乘法函数,但我必须检查num_1
的值,看它是偶数还是奇数,如果是偶数,
num_1 = num_1/2 while num_2 = 2 * num_2
然后执行乘法运算,
if num_1 odd: num_1 = (num_1 -1)/2 and num_2 = (2 * num_2) + num_2
,然后执行乘法。
有什么想法吗?
答案 0 :(得分:0)
经过一些测试后,我相信我已经确定了这个问题。不幸的是,在编写测试代码之前我没有意识到,但问题是 num_2不会归零,num_1会。并且,由于你的while循环只检查num_2,num_1只是继续为零,而num_2变得无限大,直到它不能再相乘。
以下是我用来测试它的内容,供将来参考:
class Tester:
def get_num_1(self):
return self._num_1
def set_num_1(self, value):
print("num_1", value)
self._num_1 = value
def get_num_2(self):
return self._num_2
def set_num_2(self, value):
print("num_2", value)
self._num_2 = value
num_1 = property(get_num_1, set_num_1)
num_2 = property(get_num_2, set_num_2)
def p_mult(self):
prod = 0
while self.num_2 != 0:
if (self.num_1%2 != 0): # is odd?
self.num_1 = (self.num_1-1) / 2
self.num_2 = (2 * self.num_2) + self.num_2
prod = self.num_1 * self.num_2
elif (self.num_1%2 == 0): # is even?
self.num_1 = self.num_1 / 2
self.num_2 = 2 * self.num_2
prod = self.num_1 * self.num_2
return prod
t = Tester()
t.num_1 = 5
t.num_2 = 6
t.p_mult()