为什么倒计时没作用了?
int start=GetTickCount();
int end=GetTickCount();
for(;end-start>=5000;end=GetTickCount()){
这个倒计时他会直接跳过,就好像0秒就结束了,为什么呢?
为什么倒计时没作用了?
int start=GetTickCount();
int end=GetTickCount();
for(;end-start>=5000;end=GetTickCount()){
这个倒计时他会直接跳过,就好像0秒就结束了,为什么呢?
因为end和start相隔很近,所以其相减之差应该是0,所以for循环终止条件满足,所以for循环里面没有执行。我用GetTickCount()函数编写测试倒计时代码好像有点问题,所以我用clock()函数来编写了一个倒计时的测试例子(倒计时不知道是不是很精确,但思路应该是没有太大问题,供参考),如下:
参考链接:
https://www.jb51.net/article/37860.htm
C语言double类型取余操作_deeeesn的博客-CSDN博客_double取余
GetTickCount_百度百科
#include <iostream>
#include<ctime>
#include <windows.h>
#include <math.h>
using namespace std;
int main(void){
//
// int gametime;
// cout<<"请输入倒计时时间(单位为秒):";
// cin>>gametime; //倒计时总的秒数
//
//
//
//
//
// int start=GetTickCount();
// int end=GetTickCount();
// DWORD usetime =( end-start)/1000;
// for(;gametime-usetime>=0;end=GetTickCount()){
// usetime = (int)( end-start)/1000;
// cout<<gametime-usetime<<endl;
// }
double gametime,usetime;
cout<<"请输入倒计时时间(单位为秒):";
cin>>gametime; //倒计时总的秒数
//https://www.jb51.net/article/37860.htm
clock_t begin = clock();// 开始时钟
clock_t end = clock(); //结束时钟
usetime = double(end - begin) / CLOCKS_PER_SEC ; //所用的秒数
double leftSconds = (gametime-usetime); //剩余秒数
cout<<(int)leftSconds<<endl; //打印所用的时间
double preSconds=-1; //前一次剩余的秒数
while (usetime<=gametime){ //如果倒计时没有结束,就一直打印倒计时
end = clock(); //结束时钟
usetime = double(end - begin) / CLOCKS_PER_SEC ; //所用的秒数
leftSconds = (gametime-usetime); //剩余秒数
// cout<<"leftSonds="<<leftSconds<<endl;
//https://blog.csdn.net/weixin_43768963/article/details/106072259
if(fmod(gametime-usetime,1)==0&&leftSconds!=preSconds){ //如果当前秒数没有打印,且正好是整秒数,就打印倒计时秒数
cout<<(int)leftSconds<<endl;
}
preSconds=leftSconds; //记录当前剩余秒数,用于下一次循环判断当前秒数是由已经打印
//cout<<"preSconds="<<preSconds<<endl;
}
return 0;
}