我怎样才能(安全地)除以一个最大值,得到一个浮点值?
How can I (safely) divide a maximum value, resulting in a floating point value?
我想计算换算系数。为此,我必须除以例如的最大值。 ushort 为 uchar 的最大值。
我想通过将参数传递给函数或类型名来动态执行此操作。然后我想 select 最大值并执行计算。
有两个问题:
- 如何动态地 select 最大值?
- 如何安全地划分这两个值?
已知所有值都在 double 的范围内。
理想情况下我想做这样的事情:
double x = numeric_limits<T>::max / numeric_limits<T2>::max;
然而那不是 correct/possible。
您提出的想法应该可行:
#include <iostream>
#include <limits>
template <typename T, typename T2>
double get_ratio()
{
return static_cast<double>(std::numeric_limits<T>::max()) / std::numeric_limits<T2>::max();
}
int main()
{
auto ratio = get_ratio<unsigned short, unsigned char>();
std::cout << ratio << '\n';
return 0;
}
我想计算换算系数。为此,我必须除以例如的最大值。 ushort 为 uchar 的最大值。
我想通过将参数传递给函数或类型名来动态执行此操作。然后我想 select 最大值并执行计算。
有两个问题:
- 如何动态地 select 最大值?
- 如何安全地划分这两个值?
已知所有值都在 double 的范围内。
理想情况下我想做这样的事情:
double x = numeric_limits<T>::max / numeric_limits<T2>::max;
然而那不是 correct/possible。
您提出的想法应该可行:
#include <iostream>
#include <limits>
template <typename T, typename T2>
double get_ratio()
{
return static_cast<double>(std::numeric_limits<T>::max()) / std::numeric_limits<T2>::max();
}
int main()
{
auto ratio = get_ratio<unsigned short, unsigned char>();
std::cout << ratio << '\n';
return 0;
}