[英]Why doesnt my function count?
我有一个功能,如果您在其中插入数字,它就会将它们数出来。 仅当您在程序开始时调用该函数时,它才这样做,这意味着它与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;
}
}
}
您不会在此行中调用该函数:
void countbysec(int Seconds);
您正要声明该功能。 编译器需要先查看函数的声明才能调用它,否则您将看到:
error: use of undeclared identifier 'countbysec'
它需要能够在您拨打电话时键入check并为该电话生成代码。
您可以一步一步地声明和定义函数,方法是将代码块从main()
下面移到文件中的它上面。 这是正常的C / C ++行为。
首先, clock
不是执行所需功能的正确工具。 它返回该进程已使用多少CPU时间的近似值。 近似应有一些警钟响起。 接下来,CPU时间与墙上时间不同,因此谁能说出程序运行到十秒时所经过的时间。
所以
if(clock() == counttime){
时间必须精确counttime
为了做你的计数递增。 实现这一目标的可能性不太高。 您可能会过去。 如果您这样做,将一无所获。 我建议
if(clock() >= counttime){
接下来,您不太可能获得最后一秒,因为
while(clock() <= Timer)
可能首先跳闸并退出循环。
如果要计算秒数,请查看类似std::this_thread::sleep_until
。
设置唤醒时间=当前时间+ 1秒,然后
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.