Input : 7 --> Outpu" />
登录
首页 >  Golang >  Go问答

代码编译但 for 循环没有被执行

来源:stackoverflow

时间:2024-04-30 10:48:35 466浏览 收藏

本篇文章给大家分享《代码编译但 for 循环没有被执行》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

package main

import "fmt"

// I want to make a code that outputs a series of "n" odd numbers.
// For example-> Input : 7 --> Output : 1 , 3 , 5 , 7

func main(){

var n int
var i int

fmt.Println("I'll give you a series of odd numbers to n ") // I'm asking which number do I want the series to stop.

fmt.Scanln(&n)

  if n%2 == 1 {

    for i=0 ; i >= n; i++ { // Here it's supposed to print out the series but at least something
                            // The whole code compiles but when I execute it, the program just takes the number that I ask in the Scanln
      var odd int          // and it stops there. What am I doing wrong? The for cycle? 

        odd = (i*2) - 1

      fmt.Printf(disp)

    }

  } else {

    fmt.Println("It's round") //I've put the for in an (if/else) just to see if it somehow it didn't read until the for part.
                              //But the (if/else) works but the for cycle doesn't. I'm so confused.
  }

}

解决方案


我认为您的问题在于以下行:

...
for i=0 ; i >= n; i++ {
...

for 循环的条件对于内部循环来说应该为真。

但是这里的 i 从 0 开始,并且 n 总是更高,除非您设置为 0。

i 的条件更改为小于 n 即可。

好了,本文到此结束,带大家了解了《代码编译但 for 循环没有被执行》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>