我正在解析数组中的字符串,并在解析字符串时显示进度。这是我的逻辑,但它不能扩展到小于10的输入。
除以零已经在100*i/(lineLen-1)函数的初始部分完成了。
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
}
}发布于 2017-07-09 07:55:21
我知道你需要把所有的百分比都降到10的倍数。
您可以尝试下面这样的方法。
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, "%")
}
}
}发布于 2017-07-09 13:02:05
看看https://play.golang.org/p/xtRtk1T_ZW (下面复制的代码):
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/aR6coeLhAk对outputMax和lineLen的不同值执行循环,以查看您喜欢哪个outputMax值(我认为8 <= outputMax < 13最好)。默认情况下,进度条的输出是禁用的,但您可以在main中轻松启用它。
https://stackoverflow.com/questions/44989533
复制相似问题