doudiaozhi6658 2018-07-14 20:30
浏览 155
已采纳

如何在golang中的txt文件中编写循环的输出

i'm new in go, i want to know, how to write the output of loop for in txt file in golang here my code

package main

import (
    "fmt"
    "log"
    "os"
)

func main() {

    for i := 1; i <= 10; i++ {
        if i%2 == 0 {
            continue
        }
        fmt.Printf("%d ", i)
        file, err := os.Create("result.txt")
        if err != nil {
            log.Fatal("Cannot create file", err)
        }
        defer file.Close()

        fmt.Fprintf(file, " x equal to %d", i)

    }

}

but i get 9 instead of 1 3 5 7 9 so how to fix that

  • 写回答

1条回答 默认 最新

  • dongyu4863 2018-07-14 20:46
    关注

    The problem is that you are recreating the file each iteration of the loop, which is why the only value in the file is the last value you write in the loop.

    Try the following

    package main
    
    import (
        "fmt"
        "log"
        "os"
    )
    
    func main() {
        file, err := os.Create("result.txt")
        if err != nil {
            log.Fatal("Cannot create file", err)
        }
        defer file.Close()
    
        for i := 1; i <= 10; i++ {
            if i%2 == 0 {
                continue
            }
            fmt.Printf("%d ", i)
            fmt.Fprintf(file, " x equal to %d", i)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题