首页 > 解决方案 > 双打能够代表每个 int64_t 值吗?

问题描述

using Num = std::variant<int64_t, double>;

std::vector<int64_t> intsOnly  = makeInts();
std::vector<Num> intsAndFloats = makeIntsAndFloats();

int64_t  iResult = 0;
for (auto i: intsOnlys) {
  iResult += i;
}

double dResult = 0.0;
for (auto d: intsAndFloats) {
  dResult += extractValue(d); // function always returns double type.
}

assert(iResult == int64_t(dResult));

如果变量intsAndFloats只包含整数,上述断言是否始终成立,或者在某些情况下,双精度类型不能表示某些 int64_t 值?

我的用例是我正在创建一个玩具编译器,并且我希望添加的结果类型为intor real,具体取决于 function 的参数add。喜欢:

// If any of the arguments is a real, then the result is a real; else, it's an int.
(add $a $b $c ... $n)

目前,我对参数列表进行了两次迭代:一次是查看是否存在双精度数,另一次是执行实际加法。如果可能的话,我想避免这种情况。

// Iterate over the list once, to set hasFloat. Then ...

if (hasFloat) {
  double result = 0.0;
  for (auto i: args) {
    result += isInt(i) ? getInt(i) : getFloat(i);
  }
  return returnFloat(result);
} else { // has no floats.
  int64_t result = 0;
  for (auto i: args) {
    result += getInt(i);
  }
  return returnInt(result);
}

标签: c++floating-point

解决方案


推荐阅读