效果如下图:
1、第一种
#include <stdio.h>
#include <unistd.h> // for usleep function
#include <string.h>
const char *max_bar = "[--------------------] 100%";
void printPctBar(int pct) {
int width = 20; // Width of the progress bar
int pos = width * pct / 100;
for (int i = 0; i < strlen(max_bar); i++)
{
printf("\b"); // del old char
}
fflush(stdout);
printf("[");
for (int i = 0; i < width; ++i) {
if (i < pos) printf("=");
//else if (i == pos) printf(">");
else printf("-");
}
printf("] %d%%", pct);
fflush(stdout);
}
int main() {
for (int i = 0; i <= 100; ++i) {
printPctBar(i);
usleep(50000); // Sleep for 50 milliseconds
}
printf("\n");
return 0;
}
2、第二种
#include <stdio.h>
#include <unistd.h> // for usleep function
#include <string.h>
//const char *max_bar = "[--------------------] 100%";
void printPctBar(int pct) {
int width = 20; // Width of the progress bar
int pos = width * pct / 100;
// for (int i = 0; i < strlen(max_bar); i++)
// {
// printf("\b"); // del old char
// }
printf("\r");
fflush(stdout);
printf("[");
for (int i = 0; i < width; ++i) {
if (i < pos) printf("=");
//else if (i == pos) printf(">");
else printf("-");
}
printf("] %d%%", pct);
fflush(stdout);
}
int main() {
for (int i = 0; i <= 100; ++i) {
printPctBar(i);
usleep(50000); // Sleep for 50 milliseconds
}
printf("\n");
return 0;
}
3、Python
#!/usr/bin/python3
import time
def printPctBar(pct):
pos = (50 * pct // 100)
print("\r[%s%s] %d%%" % ("▓"*pos, " "*(50-pos), pct), end="")
if __name__ == "__main__":
for i in range(101):
printPctBar(i)
time.sleep(0.05)
print("")