1
有人可以解释为什么下面的代码(打印乘法表)是不按预期工作?为什么time.sleep()延迟在嵌套while循环内无法按预期工作?
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'秒的间隔一次打印整行。