各种函数的用法
发布日期:2021-05-11 00:44:22 浏览次数:25 分类:精选文章

本文共 1963 字,大约阅读时间需要 6 分钟。

计时工具

利用 <time.h>

在C语言中,<time.h> 库提供了获取和设置当前时间的函数。常用的计时函数包括 clock()time()。以下是使用 clock() 函数进行计时的示例代码:

#include 
#include
using namespace std;
int main() {
clock_t start, end;
start = clock(); // 设置开始计时
// 在这里插入你需要测量的代码
end = clock(); // 设置结束计时
float time = static_cast
(end - start) / 1000; // 转换为秒
cout << "耗时为" << time << "秒" << endl;
system("pause");
return 0;
}

利用 <windows.h>

如果你需要更高精度的计时,<windows.h> 库提供了 GetTickCount() 函数,可以获取系统的计时周期。以下是使用 GetTickCount() 的示例代码:

#include 
#include
using namespace std;
int main() {
unsigned long long beginTime = 0;
beginTime = ::GetTickCount64(); // 获取64位计时值
// 你的代码操作
unsigned long long endTime = ::GetTickCount64();
double seconds = static_cast
(endTime - beginTime) / 1000.0;
int minutes = static_cast
(seconds / 60);
seconds -= minutes * 60;
cout << "排序耗时:" << minutes << ":" << (seconds < 10 ? "0" : "") << seconds << endl;
return 0;
}

随机数生成

在C语言中,随机数通常通过系统时间来生成随机种子。以下是使用 <stdlib.h><time.h> 库生成随机数的示例代码:

#include 
#include
#include
using namespace std;
int main() {
srand(static_cast
(time(nullptr))); // 设置随机种子
for (int m = 1; m <= 1000; ++m) {
float i = static_cast
(rand()) / 32768.0; // 生成0到1之间的随机数
cout << i << endl;
}
return 0;
}

rand() 函数的扩展用法

除了默认范围的随机数,rand() 函数可以通过以下方式扩展:

  • 生成小于 N 的随机数:rand() % N
  • 生成大于 m 小于 n 的随机数:rand() % (n - m) + m
  • 生成小数:可以将 rand() 结果转换为小数,例如:
#include 
#include
#include
#include
using namespace std;
int main() {
srand(static_cast
(time(nullptr)));
float data = static_cast
(rand() % 100000) / 10000.0; cout << fixed << setprecision(4) << data << endl; return 0; }

以上代码示例可以根据实际需求进行修改,是希望生成更精确的随机数还是其他特定范围的随机数。

上一篇:计时工具两种
下一篇:c++中 \n \t 用法

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2025年04月15日 19时13分51秒