【问题标题】:Why does my while loop not work in coffeescript?为什么我的while循环在coffeescript中不起作用?
【发布时间】:2020-06-14 01:07:13
【问题描述】:

结果被初始化为 0,但在 while 循环执行后,它的值仍然是 0。我尝试了很多,但它没有按我的预期工作。我不知道是不是因为变量声明。

armstrongNumber = (num) -> 
  originalnum = num

  result=0
  count=0
  while num != 0
     num = parseInt(num / 10)
     count++

  while num != 0
     remainder = num % 10
     result += Math.pow(remainder, count)
     num = parseInt(num / 10)


  console.log result
  console.log count
  console.log num

  if result == originalnum
     console.log "Yes, it is an Armstrong number"
  else
     console.log "It is not an Armstrong number"


armstrongNumber 12

【问题讨论】:

  • 你期待什么?
  • 执行while循环后result的值仍然为0。
  • 第二个循环永远不会运行(这是唯一触及结果的循环)。第一个循环确保 num == 0。第二个循环仅在 num != 0 时运行,这绝不是这种情况。
  • 非常感谢,我得到了错误,我的代码现在可以工作了。
  • 也许您可以发布正确的代码,然后将问题标记为已解决? :)

标签: coffeescript


【解决方案1】:
armstrongNumber = (num) -> 
  originalnum = num
  reoriginalnum=num

  result=0
  count=0

  #find the number of digits in a number
  while num != 0
    num = parseInt(num / 10)
    count++

  while reoriginalnum != 0
    remainder = reoriginalnum % 10
    result += Math.pow(remainder, count) 
#Math function pow to find the power of remainder
    reoriginalnum = parseInt(reoriginalnum / 10)

  if result == originalnum    #verify the number is armstrong or not
    console.log "Yes, it is an armstrong number"
  else
    console.log "It is not an armstrong number"

    #call the function to check: armstrongNumber 1634

【讨论】:

  • 这是正确的代码。我将 num 值分配给了两个变量 originalnum 和 reoriginalnum,因为在 while 循环之后 num 的值丢失了。
  • 欢迎来到 SO。虽然这段代码 sn-p 可能是解决方案,但包含解释确实有助于提高帖子的质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。详情请查看how-to-answer
猜你喜欢
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 2022-01-26
  • 2022-12-12
  • 1970-01-01
  • 2020-04-04
  • 1970-01-01
  • 2020-01-08
相关资源
最近更新 更多