【问题标题】:How do you multiply using while without using multiplication? [closed]如何在不使用乘法的情况下使用 while 进行乘法? [关闭]
【发布时间】:2014-11-06 20:29:14
【问题描述】:

我想知道如何只使用加法或减法运算符而不使用除法和乘法来获得两个整数的乘积。如果您可以添加会有所帮助的 while 语句。一个

基本上,我想知道如何将某个数字添加到用户定义的特定次数。将数字 x 添加到自身 y 次。要让用户定义循环次数,请使用 int()。谢谢,请在必要时使用 cmets。我对此还是有点陌生​​,谢谢。

这是我当前的代码:

# 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)

++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++

感谢您的帮助... 不过我想通了

进口时间

print ('两位数乘法计算器') 打印('====================================') 打印 () print ('给我两个数字')

x = int(输入(':'))

y = int(输入(':'))

z = 0

当 x > 0 时: 打印 (z) 打印 () x = x - 1 z = y + z time.sleep (.2)

打印 (z+x)

【问题讨论】:

  • 您不能只在此处复制/粘贴您的家庭作业。请向我们展示您已经尝试过的内容,并清楚地解释为什么它不起作用。然后,我们将很乐意提供帮助。
  • # 要求用户输入两个数字相乘 print ('Give me two numbers to multiply.') print () # 从用户那里获取输入 x = int ( input ('First Number: ')) y = int ( input ('Second Number: ')) z = 0 # 做“乘法” while z
  • 显而易见的解决方案是:z = (operator.add, operator.sub)[y&lt;0](0, functools.reduce(lambda x, y: x + y, (x for _ in range(abs(y)))))。 ;-)
  • 抱歉给大家带来了麻烦...

标签: python int operators multiplication


【解决方案1】:

你可以重复使用加法。

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

【讨论】:

    【解决方案2】:

    我不确定这是否是正确答案,因为它包含可怕的*。另一方面,它不是算术乘法... 编辑弄乱了逻辑,现在可以了

    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)
    

    【讨论】:

      【解决方案3】:

      我想如果我必须使用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
      >>> 
      

      【讨论】:

      • 这可以避免 y 的负值,但从其他 cmets 来看,这可能只是家庭作业:/ heh
      • 你的自我评论启发了我...谢谢
      猜你喜欢
      • 2014-01-23
      • 2023-04-03
      • 2014-03-13
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多