duanpanhuo0618 2016-03-25 13:26
浏览 108
已采纳

在同一行上打印多行字符串

what the title says. I have a dice program, and it prints a dice IE

 ------
|      |
|      |
|     1|
 ------

I want to be able to print multiple dice, so it looks like this:

 ------     ------
|      |   |      |
|      |   |      |
|     1|   |     3|
 ------     ------

I have tried fmt.Print, but that still prints them below each other. I was thinking about creating a function as well, that prints the top line of each object, but I couldn't figure out how to do this. Any ideas?

  • 写回答

2条回答 默认 最新

  • ds34222222 2016-03-25 14:19
    关注

    This takes care of the printing. The numbers are randomized between 1 and 6 (inclusive). The number of dice taken as a command line argument. So in my case ./roll 6 prints 6 dice with random numbers up to 6.

    package main
    
    import (
        "fmt"
        "math/rand"
        "os"
        "strconv"
        "time"
    )
    
    func main() {
        numDice := 1
    
        if len(os.Args) > 1 {
            i, err := strconv.Atoi(os.Args[1])
            if err != nil {
                fmt.Println(err)
            }
            numDice = i
        }
    
        seed := rand.NewSource(time.Now().UnixNano())
        randomNumber := rand.New(seed)
    
        die := []string{
            " ------   ",
            "|      |  ",
            "|      |  ",
            "|      |  ",
            " ------   ",
        }
    
        for i := 0; i < 5; i++ {
            for j, n := 0, numDice; j < n; j++ {
                if i == 3 {
                    fmt.Printf("|    %d |  ", randomNumber.Intn(5)+1)
                } else {
                    fmt.Print(die[i])
                }
            }
            fmt.Println()
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持