for-loop - 代码编译但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 i=0 ; i >= n; i++ {
...
for 循环的条件应该为 true 才能在内部循环。
但是这里i
从 0 开始,并且n
总是更高,除非你设置为 0。
将条件更改为i
小于n
,它将起作用。
推荐阅读
- benchmarkdotnet - 如何测量字符串实习?
- sql - BigQuery 标准 SQL 中的 typedef 等效项
- node.js - Jenkins 参数在命令行中无法识别
- autodesk-forge - MarkupsCore Extension 自定义代码后无法与 Autodesk View 交互
- python - 在熊猫中按组检查5个不同年份的值
- java - 如何在 Hibernate Criteria API 中使用 row_number(或任何具有相同行为的东西)?
- html - 如何将此代码仅转换为 HTML?
- javascript - 具有多个标题的多个图像模式
- php - 菜单滚动问题
- react-native - React Native:屏幕顶部的额外空白空间