gpt4 book ai didi

c++ - floor 和 duration_cast 有什么区别?

转载 作者:可可西里 更新时间:2023-11-01 16:36:07 25 4
gpt4 key购买 nike

所以在 Chrono 图书馆提供, duration_cast :

Computations are done in the widest type available and converted, as if by static_cast, to the result type only when finished

floor :

Returns the greatest duration t representable in ToDuration that is less or equal to d

所以对于所有x这两个调用的结果是否相等:

  1. chrono::duration_cast<chrono::seconds>(x)
  2. chrono::floor<chrono::seconds>(x)

最佳答案

据我所知,与 static_caststd::floor 之间的区别相同:负数向下舍入而不是截断为零。

#include <iostream>
#include <chrono>
using namespace std::chrono_literals;

int main() {
std::cout << "duration_cast:" << std::endl;
std::cout << "1.4s: " << std::chrono::duration_cast<std::chrono::seconds>(1400ms).count() << std::endl;
std::cout << "1.5s: " << std::chrono::duration_cast<std::chrono::seconds>(1500ms).count() << std::endl;
std::cout << "1.6s: " << std::chrono::duration_cast<std::chrono::seconds>(1600ms).count() << std::endl;
std::cout << "-1.4s: " << std::chrono::duration_cast<std::chrono::seconds>(-1400ms).count() << std::endl;
std::cout << "-1.5s: " << std::chrono::duration_cast<std::chrono::seconds>(-1500ms).count() << std::endl;
std::cout << "-1.6s: " << std::chrono::duration_cast<std::chrono::seconds>(-1600ms).count() << std::endl;

std::cout << "floor:" << std::endl;
std::cout << "1.4s: " << std::chrono::floor<std::chrono::seconds>(1400ms).count() << std::endl;
std::cout << "1.5s: " << std::chrono::floor<std::chrono::seconds>(1500ms).count() << std::endl;
std::cout << "1.6s: " << std::chrono::floor<std::chrono::seconds>(1600ms).count() << std::endl;
std::cout << "-1.4s: " << std::chrono::floor<std::chrono::seconds>(-1400ms).count() << std::endl;
std::cout << "-1.5s: " << std::chrono::floor<std::chrono::seconds>(-1500ms).count() << std::endl;
std::cout << "-1.6s: " << std::chrono::floor<std::chrono::seconds>(-1600ms).count() << std::endl;
return 0;
}

.

duration_cast:
1.4s: 1
1.5s: 1
1.6s: 1
-1.4s: -1
-1.5s: -1
-1.6s: -1
floor:
1.4s: 1
1.5s: 1
1.6s: 1
-1.4s: -2
-1.5s: -2
-1.6s: -2

https://wandbox.org/permlink/SsmpRz6RkvbL6Sru

关于c++ - floor 和 duration_cast 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48468068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com