试着做一个打勾计数器.. [英] Trying to do a tick counter..

查看:90
本文介绍了试着做一个打勾计数器..的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,我正在尝试制作一个可以算上滴答的小程序,当程序计算得足够多时,它会做点什么......

这里是代码:

  #include    <   iostream  >  
#include < stdlib.h >
#include < ctime >

使用 命名空间标准;

bool bExit = false ;
clock_t ticks = 30 ;
void setEnviroment();

int main()
{
setEnviroment();
clock_t t1 = ticks;
while (bExit!= true
{
if (t1 == ticks)
{
t1 = clock();
cout<< 每30个刻度打印一次\ n;
}
}
system( pause);
return 0 ;
}

void setEnviroment()
{
system( title Loopy squid);
}



我知道使用system()并不是一个好选择,但因为它是一个小程序,所以不应该问题..

提前致谢..

PS我没有真正使用过ctime而且我在Visual Studio 2010中工作

解决方案

看看你的代码:

< pre lang =cs> clock_t t1 = ticks;
while (bExit!= true
{
if (t1 == ticks)
{
t1 = clock();
cout<< 每30个刻度打印一次\ n;
}
}

第一次绕圈时, t1 的值为 ticks (如果你愿意,可以是30)。因此,它通过if条件测试,并将其更改为处理器使用情况。

然后再循环循环。现在,有2,147,483,646个值可能会使它失败if条件(因为 clock_t 是32位值)。



如果失败一次,它将永远不会重新输入if,所以t1永远不会再改变。





即使你解决了这个问题,你也会意识到30个滴答是不是30秒?刻度的持续时间是系统特定的,在某些系统上是15ms,而现代的那些更快,更快?



我认为你需要考虑一下这个,并停止尝试使用刻度线。

如果你想每三十秒发一条消息,那么有更好的方法可以做到这一点。提示:尝试找出当前时间......


Yeah, I was trying to make a little program that would count ticks and when the program would count enough of ticks it would do something...
Here''s the code:

#include <iostream>
#include <stdlib.h>
#include <ctime>

using namespace std;

bool bExit = false;
clock_t ticks = 30;
void setEnviroment();

int main()
{
	setEnviroment();
	clock_t t1 = ticks;
	while(bExit != true)
	{
		if(t1 == ticks)
		{
			t1 = clock();
			cout<<"Should print this every 30 ticks\n";
		}
	}
	system("pause");
	return 0;
}

void setEnviroment()
{
	system("title Loopy squid");
}


I know that using system() isn''t good choice but since it''s a small program, it shouldn''t matter..
Thanks in advance..
P.S. I haven''t really worked with ctime and I''m working in Visual Studio 2010

解决方案

Look at your code:

clock_t t1 = ticks;
while(bExit != true)
{
    if(t1 == ticks)
    {
        t1 = clock();
        cout<<"Should print this every 30 ticks\n";
    }
}

The first time you go round the loop, the value of t1 is ticks (or 30 if you prefer). So, it passes the if condition test, and changes it to the processor usage.
It then goes round the loop again. Now, there are 2,147,483,646 values which it could be that will allow it to fail the if condition (since clock_t is a 32 bit value).

If it fails once, it will never re-enter the if, and so t1 will never change again.


And even if you fix that, you do realize that 30 ticks is nothing like 30 seconds? That the duration of a tick is system specific and on some systems is 15ms, and modern ones much, much faster?

I think you need to think about this a bit, and stop trying to use ticks at all.
If you want a message every thirty seconds, there are much better ways to do it. Hint: Try finding out the current time instead...


这篇关于试着做一个打勾计数器..的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆