鱼C论坛

 找回密码
 立即注册
查看: 2688|回复: 4

两代码相同运算结果却不同。

[复制链接]
发表于 2020-3-23 07:44:37 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
[size=6]def fab(n):
    n1 = 1
    n2 = 1
    n3 = 1

    if  n < 1:
        print('输入有误1' )
        return -1

    while (n-2) > 0:
        n3= n2 + n1
        nl = n2
        n2 = n3
        n -= 1

        return n3

result = fab(20)
if result != -1:
    print('共有%d对小免惠子诞生!' % result)
为什么这个代码得到的结果是2。




def fab(n):
    n1 = 1
    n2 = 1
    n3 = 1

    if   n < 1:
        print('输入有误1' )
        return -1

    while (n-2) > 0:
        n3= n2+ n1
        n1 = n2
        n2 = n3
        n  -=1


    return n3

result = fab(20)
if result != -1:
    print ('共有几!%d对兔子'  % result)
而这个代码得到的是6765。

明明两代码是一样的,可是算出的结果却不同????
有没有大佬解答下?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-3-23 07:47:32 | 显示全部楼层
第一段代码的while循环里面,n1写成nl了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-23 09:41:44 | 显示全部楼层
def fab(n):
    n1 = 1
    n2 = 1
    n3 = 1

    if  n < 1:
        print('输入有误1' )
        return -1

    while (n-2) > 0:
        n3= n2 + n1
        nl = n2
        n2 = n3
        n -= 1

        return n3

result = fab(20)
if result != -1:
    print('共有%d对小免惠子诞生!' % result)

变量名拼错了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-23 13:05:10 | 显示全部楼层
  1. def fab(n):
  2.     n1 = 1
  3.     n2 = 1
  4.     n3 = 1

  5.     if  n < 1:
  6.         print('输入有误1' )
  7.         return -1

  8.     while (n-2) > 0:
  9.         n3= n2 + n1
  10.         n1 = n2    # 变量名错了
  11.         n2 = n3
  12.         n -= 1

  13.         return n3

  14. result = fab(20)
  15. if result != -1:
  16.     print('共有%d对小免惠子诞生!' % result)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-23 20:06:42 | 显示全部楼层
本帖最后由 S.archagnelice 于 2020-3-23 20:08 编辑

第二个代码 return缩进不对。
你的
  1. def fab(n):
  2.     n1 = 1
  3.     n2 = 1
  4.     n3 = 1

  5.     if   n < 1:
  6.         print('输入有误1' )
  7.         return -1

  8.     while (n-2) > 0:
  9.         n3= n2+ n1
  10.         n1 = n2
  11.         n2 = n3
  12.         n  -=1
  13.         return n3 #[b]正确的应该在这个位置[/b]。

  14.     #return n3  #[b]这是你的[/b]。

  15. result = fab(20)
  16. if result != -1:
  17.     print ('共有几!%d对兔子'  % result)
复制代码


对照你上面正确的那个看下这个缩进。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-30 22:54

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表