首页 > 解决方案 > 代码编译但for循环没有被执行

问题描述

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-loopgo

解决方案


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

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

for 循环的条件应该为 true 才能在内部循环。

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

将条件更改为i小于n,它将起作用。


推荐阅读