首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当输入小于10时,如何设计进度条逻辑?

当输入小于10时,如何设计进度条逻辑?
EN

Stack Overflow用户
提问于 2017-07-09 02:32:54
回答 2查看 974关注 0票数 0

我正在解析数组中的字符串,并在解析字符串时显示进度。这是我的逻辑,但它不能扩展到小于10的输入。

除以零已经在100*i/(lineLen-1)函数的初始部分完成了。

代码语言:javascript
复制
progress := 0
for i:= 0; i<lineLen;i++ {
 //.. lineLen = array length
//.....String processing...
if (100*i/(lineLen-1)) >= progress {
     fmt.Printf("--%d%s--", progress, "%")
     progress += 10
}
}
EN

回答 2

Stack Overflow用户

发布于 2017-07-09 07:55:21

我知道你需要把所有的百分比都降到10的倍数。

您可以尝试下面这样的方法。

代码语言:javascript
复制
lineLen := 4
progress := 0
for i := 0; i < lineLen; i++ {
    // Rounding down to the nearest multiple of 10.
    actualProgress := (100 * (i+1) / lineLen)
    if actualProgress >= progress {
        roundedProgress := (actualProgress / 10) * 10
        // Condition to make sure the previous progress percentage is not repeated.
        if roundedProgress != progress{
            progress = roundedProgress
            fmt.Printf("--%d%s--", progress, "%")
        }
    }
}

Link

票数 1
EN

Stack Overflow用户

发布于 2017-07-09 13:02:05

看看https://play.golang.org/p/xtRtk1T_ZW (下面复制的代码):

代码语言:javascript
复制
func main() {
    // outputMax is the number of progress items to print, excluding the 100% completion item.
    // There will always be at least 2 items output: 0% and 100%.
    outputMax := 10

    for lineLen := 1; lineLen < 200; lineLen++ {
        fmt.Printf("lineLen=%-3d    ", lineLen)
        printProgress(lineLen, outputMax)
    }
}

// Calculate the current progress.
func progress(current, max int) int {
    return 100 * current / max
}

// Calculate the number of items in a group.
func groupItems(total, limit int) int {
    v := total / limit
    if total%limit != 0 {
        v++
    }
    return v
}

// Print the progress bar.
func printProgress(lineLen, outputMax int) {
    itemsPerGroup := groupItems(lineLen, outputMax)
    for i := 0; i < lineLen; i++ {
        if i%itemsPerGroup == 0 {
            fmt.Printf("--%d%%--", progress(i, lineLen))
        }
    }
    fmt.Println("--100%--")
}

如果您愿意,您可以使用https://play.golang.org/p/aR6coeLhAkoutputMaxlineLen的不同值执行循环,以查看您喜欢哪个outputMax值(我认为8 <= outputMax < 13最好)。默认情况下,进度条的输出是禁用的,但您可以在main中轻松启用它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44989533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档