c++写一个卡时间的代码
时间: 2024-03-02 16:53:39 浏览: 15
以下是一个简单的C++代码,可以卡时间:
```
#include <iostream>
#include <chrono>
#include <thread>
int main() {
auto start = std::chrono::high_resolution_clock::now(); // 获取开始时间
std::this_thread::sleep_for(std::chrono::seconds(5)); // 程序暂停5秒钟
auto end = std::chrono::high_resolution_clock::now(); // 获取结束时间
std::chrono::duration<double> elapsed = end - start; // 计算时间差
std::cout << "程序运行时间为:" << elapsed.count() << " 秒" << std::endl;
return 0;
}
```
这个程序使用了C++11中的chrono库来计算时间,使用了thread库中的sleep_for函数来暂停程序。程序运行后会输出程序运行的时间,单位为秒。
相关问题
c++写一个用clock()卡时间的算法
以下是一个使用`clock()`函数卡时间的简单算法:
```c++
#include <iostream>
#include <ctime>
using namespace std;
int main() {
clock_t start = clock(); // 获取开始时间
// 这里是需要测试时间的代码段
for (int i = 0; i < 1000000000; i++) {
// do something
}
// 代码段结束
clock_t end = clock(); // 获取结束时间
double elapsed = (double)(end - start) / CLOCKS_PER_SEC; // 计算时间差,单位为秒
cout << "程序运行时间为:" << elapsed << " 秒" << endl;
return 0;
}
```
在这个程序中,我们使用了`clock()`函数来获取程序运行的时间。`clock()`函数返回的是程序运行的时钟周期数,我们可以通过除以`CLOCKS_PER_SEC`来将其转换为秒数。在代码段结束后,我们再次调用`clock()`函数获取结束时间,然后计算时间差并输出结果。
需要注意的是,`clock()`函数返回的时钟周期数可能会因为硬件和操作系统的不同而有所不同。另外,`clock()`函数的精度也可能不够高,不适合用于高精度时间计算。
用C++面向对象写一个抽卡模拟器的代码
好的,下面是一个简单的抽卡模拟器的代码,包含了一些基本的面向对象设计:
```
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
class Card {
public:
Card(string n, int r) : name(n), rarity(r) {}
string getName() const { return name; }
int getRarity() const { return rarity; }
private:
string name;
int rarity;
};
class Gacha {
public:
Gacha() {
cards.push_back(Card("Card A", 3));
cards.push_back(Card("Card B", 4));
cards.push_back(Card("Card C", 5));
}
Card draw() {
int r = rand() % 100;
if (r < 5) {
return Card("Card D", 6);
} else if (r < 25) {
return Card("Card C", 5);
} else if (r < 55) {
return Card("Card B", 4);
} else {
return Card("Card A", 3);
}
}
private:
vector<Card> cards;
};
int main() {
srand(time(NULL));
Gacha gacha;
for (int i = 0; i < 10; i++) {
Card card = gacha.draw();
cout << "You got " << card.getName() << " (Rarity " << card.getRarity() << ")" << endl;
}
return 0;
}
```
在这个代码中,我们定义了两个类:`Card` 和 `Gacha`。`Card` 表示每一张卡牌,它有一个名称和一个稀有度属性。`Gacha` 表示整个抽卡系统,它包含了所有的卡牌,并且定义了一个 `draw` 方法,用于随机抽卡。
在 `main` 函数中,我们创建了一个 `Gacha` 对象,并且调用了它的 `draw` 方法来进行抽卡。我们使用 `srand` 函数来设置随机数种子,以及使用 `time` 函数来获取当前时间作为种子。最后,我们循环抽了 10 张卡,并且输出了每一张卡的名称和稀有度。