2017-07-08 52 views
0

我正在解析数组中的字符串,并在解析字符串时显示进度。这是我的逻辑,但它不超过扩展为输入更少10.如何在输入小于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 
} 
} 
的初始部分期间,已经照顾
+2

只是因为你不想花时间建立一个强大的进度条..它已经完成很好 https://github.com/cheggaaa/pb – reticentroot

+0

我会建议使用现有的库以及。没有理由重新发明轮子。 –

回答

1

我知道您需要将所有百分比都设为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, "%") 
     } 
    } 
} 

Link

1

看一看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看到执行过的outputMaxlineLen各种值循环您喜欢的值为outputMax8 <= outputMax < 13最适合我)。进度条的输出在默认情况下是禁用的,但您可以在main中轻松启用它。