How to convert integer to double implicitly?

int a{5},b{2},c{9};
double d = (double)a / (double)b + (double)c;

Or I can use static_cast. In any case, it is verbose, especially when the formula is long. Is there a better solution?

+6
source share
3 answers

You can multiply by 1.0:

int a{5}, b{2}, c{9};
double d = 1.0 * a / b + 1.0 * c;

And when you work with amounts, you can add to 0.0:

double d = 0.0 + a - b + c;

Most compilers perform optimizations so that a meaningless operation is not evaluated. Only type conversion is performed.


Remember that you only need to play the first term in each division / multiplication group. Do this in any way that seems reasonable. And simple addition / subtraction (without multipliers / dividers of another type) is also performed. Compilers guarantee casting. So your example:

double d = (double)a / (double)b + (double)c;

:

double d = (double)a / b + c;
double d = 1.0 * a / b + c;
double d = static_cast<double>(a) / b + c;

:

double d = (double)a / b + (double)c / d + e;
double d = 1.0 * a / b + 1.0 * c / d + e;
double d = static_cast<double>(a) / b + static_cast<double>(c) / d + e;
+6

?

. - .

, . , :

#include <iostream>

auto a_over_b_plus_c(double a, double b, double c)
{
  double d = a / b + c;
  return d;
}

int main()
{
  int a = 5, b = 2, c = 9;

  std::cout << a_over_b_plus_c(a, b, c) << std::endl;
}

, :

#include <iostream>
#include <tuple>

template<class T, class...Args> 
auto to(Args&&...args)
{
  return std::make_tuple(T(std::forward<Args>(args))...);
}

int main()
{
  int a = 5, b = 2, c = 9;

  auto calc = [](auto&& vals) {
    auto& a = std::get<0>(vals);
    auto& b = std::get<1>(vals);
    auto& c = std::get<2>(vals);

    return a / b + c;
  };

  auto result = calc(to<double>(a, b, c));

  std::cout << result << std::endl;
}

... - ...

#include <iostream>
#include <tuple>
#include <complex>

template<class T, class F, class...Args> 
auto with(F f, Args&&...args)
{
  return f(T(std::forward<Args>(args))...);
}



int main()
{
  int a = 5, b = 2, c = 9;

  auto calc = [](auto&& a, auto&& b, auto&& c) {

    return a / b + c;
  };

  auto result = with<double>(calc, a, b, c);
  auto result2 = with<float>(calc, a, b, c);
  auto result3 = with<std::complex<double>>(calc, a, b, c);
  auto result4 = with<std::complex<float>>(calc, a, b, c);

  std::cout << result << std::endl;
  std::cout << result2 << std::endl;
  std::cout << result3 << std::endl;
}
+3

, , , 1.0* a

int a{5},b{2},c{9};
double d = (double)a / (double)b + (double)c;

int a{5},b{2},c{9};
double d = 1.0*a / b + c;

, .

, 1.0* 0.0+ :

int a{5},b{2},c{9};
double d = a / (0.0 + b + c);

int a{5},b{2},c{9};
double d = a / (1.0 * b * c);

Alternatively, one use uses static casting to the associated variable. I prefer the smaller version, since 1.0*either 0.0+both shout out the implicit conversion to double.

int a{5},b{2},c{9};
double d = a / (static_cast<double>(b) * c);
0
source

All Articles