消耗每月能源成本的算法

时间:2014-11-02 13:18:29

标签: python

这运行正常,但不会产生我需要的结果。我的猜测是我在数学中遗漏了一些简单的东西。这就是我确定的问题所在。

bill = 0
months = 12
kwhour = .06
kwhour2 = .08

for months in range(1, months+1):

    month_start = int(input('month ' + str(months) + ' starting reading: '))
    month_end = int(input('month ' + str(months) + ' ending reading: '))

    if month_end <= 1000:
        output1 = month_end * kwhour
        output1 += 1
    else:
        output2 = month_end * kwhour2
        output2 += 1

        bill = output1 + output2

print('Your yearly bill is: ', bill)

if bill < 500:
    print('Thanks for saving so much energy')

4 个答案:

答案 0 :(得分:2)

首先,您需要将变量 output1和output2初始化为零,然后总帐单添加应该在 if和else 循环之外。你可以像这样重写:

   bill = 0
   months = 12
   kwhour = .06
   kwhour2 = .08
   output1=0
   output2=0

  for months in range(1, months+1):

      month_start = int(input('month ' + str(months) + ' starting reading: '))
      month_end = int(input('month ' + str(months) + ' ending reading: '))

         if month_end <= 1000:
              output1 = month_end * kwhour
              output1 += 1
         else:
              output2 = month_end * kwhour2
              output2 += 1

         bill += output1 + output2

 print('Your yearly bill is: ', bill)

 if bill < 500:
     print('Thanks for saving so much energy')

我得到了以下输出:

     ('Your yearly bill is: ', 47.03999999999999)
     Thanks for saving so much energy

答案 1 :(得分:0)

您在每个循环中重新分配账单

bill = output1 + output2

尝试添加

bill += output1 + output2

另外,你真的不需要输出1和输出2,而是直接添加到账单

if month_end <= 1000:
    bill += month_end * kwhour
    bill += 1 # I dont see why you add 1 here
else:
    bill += month_end * kwhour2
    bill += 1

答案 2 :(得分:-1)

而不是for months执行for month因为月份已经被声明为变量。你不应该用它来迭代。第二,将账单更新为bill=bill+output1+output2

答案 3 :(得分:-1)

根据我的理解,您每个月末都会阅读energy meter (counter)的值。您应该计算每个月末和每月初的读数之间的差异。那个月你消耗的是什么。然后,将你消耗的东西乘以正确的每小时因子kwhour / kwhour2并每次求和。我仍然不明白他每次都加一个(但他可以解释)。 您不需要bill += output1 + output2来添加您不需要添加的内容,这就是您添加if condition的原因。

'bill= output1+output2'没有解决问题。想象一下,如果你循环并进入案例<=1000(更新输出1),下次你进入案例>1000(更新输出2)。第三次,如果你遇到任何情况(让我们说更新&#39;输出1&#39;),你将添加一个过时的值&quot; output2&#39;开单。你应该在每个块(bill+=output1 / bill+=output2

中单独添加output1 / 2
   bill = 0
   months = 12
   kwhour = .06
   kwhour2 = .08
   output1=0
   output2=0

  for m in range(1, months+1):

      month_start = int(input('month ' + str(m) + ' starting reading: '))
      month_end = int(input('month ' + str(m) + ' ending reading: '))

         if (month_end-month_start) <= 1000:
              output1 = (month_end-month_start) * kwhour
              #output1 += 1
              bill+=output1
         else:
              output2 = (month_end-month_start) * kwhour2
              #output2 += 1
              bill+=output2

         #bill += output1 + output2 You don't need this, u gonna re-adding things 

 print('Your yearly bill is: ', bill)

 if bill < 500:
     print('Thanks for saving so much energy')