Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I (safely) divide a maximum value, resulting in a floating point value?

Tags:

c++

max

division

I want to calculate conversion factors. For this I have to divide the maximum value of e.g. ushort by the maximum value of uchar.

I want to do this dynamically, by passing a parameter into a function or a typename. Then I want to select the max values and perform the calculation.

There are two problems:

  1. How do I dynamically select the max value?
  2. How can I safely divide the two values?

All values are known to fit into the range of double.

Ideally I would want to do something like:

double x = numeric_limits<T>::max / numeric_limits<T2>::max;

However that is not correct/possible.


1 Answers

Your proposed idea should work:

#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;
}

demo

like image 92
wally Avatar answered Nov 21 '25 22:11

wally



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!