英文:
How can I check over-/underflow when converting double to int in C++?
问题
当学习关于static_cast
和dynamic_cast
时,我看到了一个关于在将double
类型转换为int
类型时进行溢出和下溢的额外检查的建议。我该如何在这里执行这个操作?
double value1{ 4.8967 };
int value2 = static_cast<int>(value1);
std::cout << value2 << std::endl;
我尝试在这里和那里搜索,只找到了算术溢出/下溢,似乎不太适用于这种情况。我会很感激如果您能提供一些我可以更详细了解这个问题的链接。
英文:
when learning about static_cast and dynamic_cast i saw an advice about additional checking on overflow and underflow when casting double type into int one. how can i do that here?
double value1{ 4.8967 };
int value2 = static_cast<int>(value1);
std::cout << value2 << std::endl;
i tried searching here and there only to found an arithmetic over-/underflow which seems not quite the case here. i'd appresiate a couple of links where i can read about it more specifically
答案1
得分: 2
你可以使用 std::numeric_limits
创建一个辅助函数来避免溢出。如果有下溢,则可以获得最小可能的 int
值,如果有溢出,则可以获得最大可能的 int
值。
#include <iostream>
#include <limits> // numeric_limits
template <class R, class T>
R anti_overflow_clamp(T value) {
if (value <= std::numeric_limits<R>::lowest()) [[unlikely]]
return std::numeric_limits<R>::lowest();
if (std::numeric_limits<R>::max() <= value) [[unlikely]]
return std::numeric_limits<R>::max();
return static_cast<R>(value);
}
int main() {
double value1 = -9872034875209384574237698276453978264398576.0;
auto value2 = anti_overflow_clamp<int>(value1);
std::cout << value2 << '\n'; // int 的最小值
}
英文:
You could use std::numeric_limits
create a helper function to avoid overflowing. You'd then get the minimum possible int
value if there would be an underflow or the maximum possible int
value if there would be an overflow.
#include <iostream>
#include <limits> // numeric_limits
template <class R, class T>
R anti_overflow_clamp(T value) {
if (value <= std::numeric_limits<R>::lowest()) [[unlikely]]
return std::numeric_limits<R>::lowest();
if (std::numeric_limits<R>::max() <= value) [[unlikely]]
return std::numeric_limits<R>::max();
return static_cast<R>(value);
}
int main() {
double value1 = -9872034875209384574237698276453978264398576.0;
auto value2 = anti_overflow_clamp<int>(value1);
std::cout << value2 << '\n'; // min value for int
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论