gpt4 book ai didi

c - 在开始时使用 "\r"更新进度条字符串,跳过或错过迭代

转载 作者:太空宇宙 更新时间:2023-11-04 11:57:07 24 4
gpt4 key购买 nike

我想用 C 语言编写一个简单的进度条函数以供进一步使用,但出现了问题。在通过“\r”更新进度条字符串并打印其新值时,函数错过或跳过了迭代。

我做了 a video您可以看到该函数正在为每次迭代正确计算和构建字符串,但是当我在字符串的开头添加“\r”时,它开始跳过迭代。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void render_progress_bar( int, int, int, char, char );

int main( void ) {
for ( int i = 1; i <= 60; i++ ) {
render_progress_bar( i, 60, 50, '#', ' ' );
usleep( 64000 );
}

return EXIT_SUCCESS;
}

void render_progress_bar( int current_iteration,
int total_iterations,
int length_of_bar,
char filled_bar_char,
char non_filled_bar_char ) {
// Calculating amount of percents reached at current iteration
double percents = (double) current_iteration / total_iterations * 100;
// Calculating amount of chars to fill in progress bar string
int amount_to_fill = length_of_bar * current_iteration / total_iterations;

// Prepaering bar string
char * bar_string = malloc( length_of_bar + 2 );
bar_string[ 0 ] = '['; bar_string[ length_of_bar + 1 ] = ']';
memset( bar_string + 1, filled_bar_char, amount_to_fill );
memset( bar_string + amount_to_fill + 1, non_filled_bar_char, length_of_bar - amount_to_fill );

// Printing the rendered progress string
printf( "Progress: %s %02.1lf Completed...\n", bar_string, percents );

// If reached 100% print new line
if ( current_iteration == total_iterations ) printf( "\n" );
}

我想要得到的结果显示在这个video中.执行完全相同但正确的 python 代码:

from time import sleep

print( '[*] Starting ...' )
sleep( 1 )

for i in range( 1, 61 ) :
# Calculating completed percents and length of bar to fill as completed
percents = '%.2f' % ( i / 60 * 100 )
filled_area = int( 50 * i / 60 )

# Preparing progress bar string
bar_string = ( '█' * filled_area ) + ( ' ' * ( 50 - filled_area ) )

# Printing progress bar with some info and EOL if reached 100%
print( '\rProgress: [%s] %s%% Completed ...\r' % ( bar_string, percents ), end = '' )
if i == 60 : print( )

sleep( 0.1 )

最佳答案

我没有看到任何遗漏的迭代。

但是,我确实看到百分比计算是在整数数学(总是四舍五入)中完成的,而不是在 double 数学中

关于c - 在开始时使用 "\r"更新进度条字符串,跳过或错过迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53898523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com