我想知道如何仅使用加法或减法运算符并且不使用除法和乘法来获得两个整数的乘积。如果你可以添加有用的while语句。甲
基本上,我想知道如何按用户定义的次数添加特定次数。将数字x添加到自身y次。要让用户定义循环它的次数,请使用int()。谢谢,请在必要时使用评论。我对此仍然有点新意,谢谢。
这是我目前的代码:
# Asks user for two numbers to multiply
print ('Give me two numbers to multiply.')
print ()
# Gets input from the user
x = int ( input ('First Number: '))
y = int ( input ('Second Number: '))
z = 0
# Does the "multipling"
while z <= x*y:
print (z)
z = z + x
time.sleep(.2)
+++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++
感谢您的帮助...... 我想通了
导入时间
打印(&#39;两位数乘法计算器&#39;) 打印(&#39; ===================================&#39;) print() 打印(&#39;给我两个号码。&#39;)
x = int(输入(&#39;:&#39;))
y = int(输入(&#39;:&#39;))
z = 0
而x> 0: 打印(z) print() x = x - 1 z = y + z time.sleep(.2)
print(z + x)
答案 0 :(得分:2)
您可以重复使用添加。
def multiply(a,b):
total = 0
counter = 0
while counter < b:
total += a
counter += 1
return total
>>> multiply(5,3)
15
想一想,要乘以两个整数,你只需多次添加一个整数。例如:
5 x 3 = 5 + 5 + 5 = 15
答案 1 :(得分:1)
我不确定这是否是正确答案,因为它包含可怕的*
。另一方面,它不是算术乘法... 编辑弄乱了逻辑,现在没关系
def prod(a,b):
if a<0 and b<0:
a, b = -a, -b
elif b<0:
b, a = a, b
return sum([a]*b)
答案 2 :(得分:0)
我想如果我必须使用while
而不是任何乘法,那么它是否与列表一致? :/
def weird_times(x, y):
my_factors = [x for _ in range(y)]
answer = 0
while my_factors:
answer += my_factors.pop()
return answer
>>> weird_times(5, 0)
0
>>> weird_times(5, 1)
5
>>> weird_times(5, 3)
15
>>>