fledgling 发表于 2022-2-27 13:23:20

求存款翻倍的问题

求存款几年后翻倍,我的结果为什么是无限循环的?。。。
capital = 10000
rate = 0.0325
year = 0
while capital< capital*2:
    capital = capital + (capital*rate)
    year = year + 1
    print(year,capital)

傻眼貓咪 发表于 2022-2-27 13:30:42

本帖最后由 傻眼貓咪 于 2022-2-27 13:31 编辑

因为 capital 的值一直在改变啊(越来越大,已经不是第一次的 capital 了,永远达不到退出条件)

c_cpp_python 发表于 2022-2-27 13:34:26

在循环前把 2*capital 的值赋给另一个变量,然后将这个新的变量跟 capital 比较

isdkz 发表于 2022-2-27 14:00:52

因为你的循环条件 capital< capital*2 恒成立,

在循环条件中,不止左边的 capital 会变,右边的 capital 也会变的,

一个正数肯定会小于它的两倍了,所以你应该用两个不同的变量,故对你的代码修改如下:

capital_old = 10000
rate = 0.0325
year = 0
capital_new = capital_old
while capital_new < capital_old * 2:
    capital_new += capital_old * rate
    year = year + 1
    print(year,capital_new)

大马强 发表于 2022-2-27 15:49:23

这个不是数学问题吗
相当于 假设一个数 y满足
y < y x n ,如果这个要成立的话 n满足 n > 1
while capital< capital*2:
此时你的n 是 2 , y是capital,这不是就是永真了

fledgling 发表于 2022-2-27 16:00:33

大马强 发表于 2022-2-27 15:49
这个不是数学问题吗
相当于 假设一个数 y满足
y < y x n ,如果这个要成立的话 n满足 n > 1


谢谢大神,懂了
页: [1]
查看完整版本: 求存款翻倍的问题