【问题标题】:Quick Inquiry About My Program快速查询我的计划
【发布时间】:2016-11-21 18:07:51
【问题描述】:

我目前正在为 python 进行编程概念课程,这是我的作业之一。我基本上不得不通过加法相乘。我已经到了我需要完成的所有事情的地步,但这在这里是额外的功劳。我已经提交了作业,但现在我在这里只是想问为什么这不起作用。

问题是当yMult 变量是浮点数时它不起作用。我认为正在发生的事情是我的计数器(因为老师希望我们用循环和计数器来做)每次都增加 1,如果我有一个浮点数作为 yMult 它不会让xMult 上升,比如 0.5。我会做些什么来解决这个问题和/或它会是什么样子?

这是我编写的代码:

def add(xAdd, yAdd):    
     return xAdd + yAdd

def subtract(xSub, ySub):    
     return xSub + (-ySub)

def multiply(xMult, yMult):    
     total = 0.0    
     counter = 0.0    
     while counter > yMult:      
         if yMult <= 0.0:
             total = add(total, -xMult)
             counter = add(counter, -1.0)
     while counter < yMult:
         if yMult >= 0.0:
             total = add(total,xMult)
             counter = add(counter, 1.0)
     return total

def main():
    print multiply (5.5,9), multiply(9,5.5), multiply(2,4), multiply(2,-4), multiply(-4,2), multiply(-4,-2), multiply(4,1), multiply(1, 4), multiply(4, 0), multiply(0, 4), multiply(4, -1)

main()

结果如下:49.5 54.0 8.0 -8.0 -8.0 8.0 4.0 4.0 0.0 0.0 -4.0

任何帮助都会很棒!

【问题讨论】:

    标签: python addition


    【解决方案1】:

    我不确定你是否可以在没有乘法的情况下解决这个问题。
    如果你想乘以 0.5,那么你需要添加另一个数字的一​​半,这意味着将它乘以 0.5。
    但是,如果您保证收到至少一个整数,那么您可以将其用作计数器:

    def multiply(xMult, yMult):    
     total = 0.0    
     counter = 0.0    
     limit = yMult
     toAdd = xMult
     if isinstance(xMult,int):   
        limit = xMult 
        toAdd = yMult
     while counter <abs(limit):      
         if limit <= 0.0:
             total = add(total, -toAdd)
         else:
             total = add(total,toAdd)
         counter = add(counter, 1.0)
     return total
    

    【讨论】:

    • 是的,我知道如何用乘法来做到这一点,但问题是教授明确表示在问题的任何地方都没有乘法 XD
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 2013-08-31
    • 2013-09-20
    • 1970-01-01
    • 2022-11-29
    • 2017-11-08
    相关资源
    最近更新 更多