0

我正在做一个有趣的项目,我将进行一些计算,我需要一些帮助。

我的程序中的一个模块:

def ARK(rawArk):
    refArk = rawArk/200
    arkTrit = refArk*300
    arkMeg = refArk*333
    arkZyd = refArk*166
    print "Totals from your Arkonor:"
    print "Tritanium=", arkTrit
    print "Megacyte=", arkMeg
    print "Zydrine=", arkZyd
    return arkTrit, arkMeg, arkZyd

现在它只是做简单的除法和乘法。我想要做的是能够用余数做到这一点。

因此,如果 'refArk = rawArk/200' 总共给出 16.3,我希望能够将 16.0 和 0.3 分开并将它们用作单独的变量以进行单独的计算。

至今:

def ARK(rawArk):
    refArk = float(rawArk/200)
    arkTrit = refArk*300
    arkMeg = refArk*333
    arkZyd = refArk*166
    print "Totals from your Arkonor:"
    print "Tritanium=", arkTrit
    print "Megacyte=", arkMeg
    print "Zydrine=", arkZyd
    strval = str(refArk)
    head,tail = strval.split(".")
    whole = float(head)
    frac = float("."+tail)
    print whole
    print frac
    return arkTrit, arkMeg, arkZyd

def main():
    rawArk=input("How much Arkonor?")
    ARK(rawArk)
    return

main()

使用“450”作为我的输入值

返回

How much Arkonor?450
Totals from your Arkonor:
Tritanium= 600.0
Megacyte= 666.0
Zydrine= 332.0
2.0
0.0

2.0 是对的,但 0.0 应该是 0.25

从 'rawArk/200' 中删除 float() 会产生一个错误:

How much Arkonor?450
Totals from your Arkonor:
Tritanium= 600
Megacyte= 666
Zydrine= 332

Traceback (most recent call last):
  File "E:\eve stuff\Calculator\test.py", line 23, in <module>
    main()
  File "E:\eve stuff\Calculator\test.py", line 20, in main
    ARK(rawArk)
  File "E:\eve stuff\Calculator\test.py", line 11, in ARK
    head,tail = strval.split(".")
ValueError: need more than 1 value to unpack
4

4 回答 4

1

可能是先使用轮函数,然后使用拆分

refArk = refArk.split(".")
于 2012-06-26T18:17:15.357 回答
1

数值上

val1 = 22.0
val2 = 7.0
whole,frac = divmod(val1,val2)
frac = frac/val1

有点黑客,但有字符串

val = 22.0/7.0
strval = str(val)
head,tail = strval.split(".")
whole = float(head)
frac = float("."+tail)

无论哪种方式

>>> frac
0.14285714286000001
>>> whole
3.0
于 2012-06-26T18:17:42.450 回答
1

为什么不这样做:

intpart=int(variable)
decimalpart=variable-intpart

I would guess this to be more efficient than casting to a string and then splitting.

于 2012-06-26T18:24:14.143 回答
0

IDLE 的以下会议将展示如何解决您的问题。

>>> lis=str(refArk).split('.')
>>> lis[-1]='.'+lis[-1]
>>> map(float,lis)
[16.0, 0.3]
于 2012-06-26T18:16:50.723 回答