2017-04-23 139 views
0

我有一个函数,如果你插入一个数字,它会计数出来。它只会在程序开始时调用该函数,这意味着它与clock()有关。我添加了clock()给其余的变量,但函数不计数。特别是在if语句中。为什么我的功能不算?

代码:

#include <stdio.h> 

#include <string> 
#include <iostream> 
#include <stdlib.h> 
#include <windows.h> 
#include "math.h" 
#include <time.h> 
#include <ctime> 
#include <cstdlib> 
#include <mmsystem.h> 

void countbysec(int Seconds); 
using namespace std; 

int main(){ 
int secondsinput; 

cout<<"Type how many seconds to cout \n"; 
cin>>secondsinput; 

countbysec(secondsinput); 

return 0; 
} 

void countbysec(int Seconds){ 
    clock_t Timer; 
    Timer = clock() + Seconds * CLOCKS_PER_SEC ; 

    clock_t counttime = clock() + (Timer/Seconds); 
    clock_t secondcount = 0; 

    while(clock() <= Timer){ 

    if(clock() == counttime){ 
    counttime = counttime + CLOCKS_PER_SEC; 
    secondcount = secondcount + 1; 

    cout<<secondcount<<endl; 
    } 
    } 
} 
+1

请注意,这是有点不规律的大写你的变量。在传统上保留用于类的C++中。这会让你的代码像“Timer”一样被读取,但事实并非如此。 – tadman

+1

“它将它们计数出来。”不知所云。请用足够的作品来清楚地说出你的意思。 – philipxy

+0

它适合我。 – Neil

回答

1

你不调用这一行的功能:

void countbysec(int Seconds);

你向前声明函数。编译器需要看到之前你可以调用它的函数的声明,否则,你会看到:

error: use of undeclared identifier 'countbysec'

它需要能够输入检查,并为你做点调用的代码电话。

您可以通过将代码块从main()以下的代码块移动到文件中的代码块上来声明和定义该功能。这是正常的C/C++行为。

0

首先,clock不是正确的工具,它看起来像你想要的。它返回进程使用了​​多少CPU时间的近似值。逼近应该有一些警钟响起。接下来,时间CPU时间与墙壁时间不一样,所以谁可以说程序工作时间达到了十秒钟的时间流逝了多少时间。

所以

if(clock() == counttime){ 

的时间必须精确counttime为了做你的计数递增。拉断这个可能性不大。你可能会拍摄过去。如果你这样做,什么都不会算。我建议

if(clock() >= counttime){ 

接下来,你不可能拿到最后一秒,因为

while(clock() <= Timer) 

可能跳闸第一和退出循环。

如果要计算秒数,请参阅something like std::this_thread::sleep_until

组唤醒时间=当前时间+ 1秒,然后

  1. 睡到唤醒时间,
  2. 计数,
  3. 添加第二个到唤醒时间,
  4. 重复,直到完成。
相关问题