c++ - 双打能够代表每个 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 值?
我的用例是我正在创建一个玩具编译器,并且我希望添加的结果类型为int
or 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);
}
解决方案
推荐阅读
- java - 使用 Siddhi 与 NATS 服务器的连接问题
- google-apps-script - 说明如何创建触发器(从下拉列表中选择一个值)以在 Google 表格中打开特定侧边栏的简单示例
- sql - Need Help for SQL MIN MAX Group By and AGGREGATE
- node.js - 具有身份验证(后端)的 asp.net 核心 webapi 和独立工作的具有身份验证的 redux 应用程序(前端)
- linux - How to reliably detect dropped netlink requests or responses
- selenium-webdriver - Katalon:使用 switchTo 和 waitForElementClickable 后无法单击对象
- javascript - Blur event cancels click event in Vue component
- asp.net-core - 身份在本地主机上工作正常,但在服务器上出现错误
- python - 使用adjustText避免标签重叠与Python王子对应分析
- python - 敌人.rect 不更新