用DEV_c++怎么编 计算程序运行时间
#include<stdio.h>#include<stdlib.h>#include<time.h>#include<unistd.h>intmain(){clock_...
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
# include <unistd.h>
int main()
{
clock_t cBegin = clock();
// do something...
sleep(1);
clock_t cEnd = clock();
printf ("%f",cBegin/ CLOCKS_PER_SEC);
printf ("%f",cEnd/ CLOCKS_PER_SEC);
printf("execution time: %f s", (cEnd - cBegin) / CLOCKS_PER_SEC);
return 0;
}
我的输出不管怎么样都是0;
求解; 展开
#include<stdlib.h>
#include<time.h>
# include <unistd.h>
int main()
{
clock_t cBegin = clock();
// do something...
sleep(1);
clock_t cEnd = clock();
printf ("%f",cBegin/ CLOCKS_PER_SEC);
printf ("%f",cEnd/ CLOCKS_PER_SEC);
printf("execution time: %f s", (cEnd - cBegin) / CLOCKS_PER_SEC);
return 0;
}
我的输出不管怎么样都是0;
求解; 展开
- 你的回答被采纳后将获得:
- 系统奖励15(财富值+成长值)+难题奖励30(财富值+成长值)
1个回答
展开全部
由于cBegin和cEnd本质是一个long int 变量,CLOCKS_PER_SEC是一个int常量,所以当它们相除结果小于1的,会自动向下取整得到0;
解决方法:将cBegin和cEnd强制转化成float类型即可;例如:
把printf ("%f",cBegin/ CLOCKS_PER_SEC);变为printf ("%f",float(cBegin)/ CLOCKS_PER_SEC);
把printf ("%f",cEnd/ CLOCKS_PER_SEC);变为printf ("%f",float(cEnd)/ CLOCKS_PER_SEC);
把printf("execution time: %f s", (cEnd - cBegin) / CLOCKS_PER_SEC);
变为printf("execution time: %f s", float(cEnd - cBegin) / CLOCKS_PER_SEC);
解决方法:将cBegin和cEnd强制转化成float类型即可;例如:
把printf ("%f",cBegin/ CLOCKS_PER_SEC);变为printf ("%f",float(cBegin)/ CLOCKS_PER_SEC);
把printf ("%f",cEnd/ CLOCKS_PER_SEC);变为printf ("%f",float(cEnd)/ CLOCKS_PER_SEC);
把printf("execution time: %f s", (cEnd - cBegin) / CLOCKS_PER_SEC);
变为printf("execution time: %f s", float(cEnd - cBegin) / CLOCKS_PER_SEC);
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询