Go语言代码编译正常但for循环未执行,无法生成指定奇数序列
Hey there! Let's break down why your for loop isn't running—you're really close, just a couple of tiny missteps getting in the way. 😊
The Core Issues
Let's go through the problems one by one:
Backwards Loop Condition
Your for loop usesi=0 ; i >= n; i++—when you input an odd number like 7,istarts at 0, and 0 is definitely not greater than or equal to 7. So the loop never even starts! That's why your program stops right after taking input. You need the condition to check ifiis still less than or equal to n, not the other way around.Undefined
dispVariable
You tried usingfmt.Printf(disp)butdispisn't defined anywhere in your code. Even if the loop ran, this would throw a compilation error. You want to print the calculatedoddvalue instead.Incorrect Odd Number Calculation
Wheni=0, your formula(i*2)-1gives-1—that's not the first odd number you want! Startingifrom 1 would fix this, but there's an even simpler way to iterate over odds directly.
Corrected Code
Here's a fixed version of your code that works as expected:
package main import "fmt" // Outputs a series of odd numbers up to n // Example: Input 7 → Output 1, 3, 5, 7 func main(){ var n int fmt.Println("I'll give you a series of odd numbers up to n ") fmt.Scanln(&n) if n%2 == 1 { // Start at 1, increment by 2 to skip even numbers, stop at n for i := 1; i <= n; i += 2 { fmt.Printf("%d, ", i) } } else { fmt.Println("It's even (not an odd number)") } }
Bonus: Fix the Trailing Comma
If you want to get rid of the extra comma at the end of the output, here's a tweaked version:
package main import "fmt" func main(){ var n int fmt.Println("I'll give you a series of odd numbers up to n ") fmt.Scanln(&n) if n%2 == 1 { // Print the first odd number separately fmt.Print(1) // Then print the rest with a leading comma for i := 3; i <= n; i += 2 { fmt.Printf(", %d", i) } fmt.Println() // Add a clean newline at the end } else { fmt.Println("It's even (not an odd number)") } }
What Changed?
- Loop Logic: Instead of calculating odd numbers from an index, we directly iterate over odd values by starting at 1 and adding 2 each time—this is more straightforward and avoids calculation errors.
- Fixed Condition: The loop now runs as long as
i <= n, so it covers all odds up to your input number. - Valid Print Statement: We replaced the undefined
dispwith a direct print of the odd number, using the correct format specifier. - Clearer Message: Updated the even-number message to be more precise (since "round" might be a translation quirk).
内容的提问来源于stack exchange,提问作者Eita Finn Sano

