繁体   English   中英

为什么time.sleep()延迟在嵌套的while循环内无法正常工作?

[英]Why time.sleep() delay doesn't work as intended inside the nested while loop?

有人可以解释为什么以下代码(用于打印乘法表) 未按预期工作吗?

import time
n = int(input("Enter number of multiples: "))
k = int(input("Enter number of tables: "))
c = 1
m = 1 #multiple
while m <= n:
    while c <= k:
        print("%4d" % (c*m), end='')
        c+=1
        time.sleep(1) #slower behaviour
    m+=1
    c=1
    print("")

奇怪的是,它不是以一秒钟的间隔打印单个水平元素,而是以“ k”秒的间隔一次打印整个行。

实际上,用C编写的代码表现出相同的行为。

#include<stdio.h>
#include<unistd.h>
void main(){
    int n,k,c=1,m=1;
    printf("Enter number of Multiples: ");
    scanf("%d",&n);
    printf("Enter number of tables: ");
    scanf("%d",&k);
    while(m<=n){
        while(c<=k){
            printf("%4d",(c*m));
            c+=1;
            //sleep(1); //slower here
        }
        m+=1;
        c=1;
        sleep(1); //faster here
        printf("\n");
    }
}

也就是说,不是打印元素并等待一秒钟,而是以“ k”秒的间隔一次打印了整行。

您告诉print跳过换行符,但是终端输出是行缓冲的。 您需要刷新数据。

print("%4d" % (c*m), end='', flush=True)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM