0

我是 python 的初学者,这个作业要求我获得投资的未来价值。

p = raw_input("[How much did you invest?]:")
r = str(raw_input("[How much is the interest rate?]:"))
n = raw_input("[How long have you been investing?]:")
future_value = p*(1+1)**n
print "\n\n\tYour future value of your investment is: %s\n" % future_value

错误代码:

unsupported operand type(s) for ** or pow(): 'int' and 'str'

有什么帮助吗?

4

2 回答 2

1

您需要将输入转换为,int因为raw_input函数返回一个string

如果您help(raw_input)在交互式终端中输入,您应该会看到定义:

raw_input(...)
    raw_input([prompt]) -> string

固定代码:

p = int(raw_input("[How much did you invest?]:"))
r = float(raw_input("[How much is the interest rate?]:"))
n = int (raw_input("[How long have you been investing?]:"))
future_value = p*(1+1)**n
print "\n\n\tYour future value of your investment is: %s\n" % future_value
于 2013-09-22T01:56:33.613 回答
1

错误消息告诉您您正在尝试将整数提高到字符串幂。那一定是这部分代码:

(1+1)**n

事实上,1+1 是一个整数(它是 2 - 如果 2 是你想要的,为什么不写 2 而不是1+1?)。

那是什么nn是从raw_input()电话中获得的。而且,确实,raw_input()总是返回一个字符串。如果您想将该字符串更改为整数(您可以),请改为执行以下操作:

n = int(raw_input("[How long have you been investing?]:"))
于 2013-09-22T01:57:57.183 回答