solidity - uint乘法与solidity中的分数
问题描述
我试图获得一个可靠值的上下阈值。
function foo(uint value) public {
uint lower_threshold = value * 0.5;
uint upper_threshold = value * 1.5;
}
使用上面的代码,我收到以下错误:
TypeError: Operator * not compatible with types uint32 and rational_const 1 / 2
我的目标是检查传递的值是否在阈值内以执行某些操作。有没有办法在 Solidity 中做到这一点?
解决方案
正如文档所说,Solidity还不完全支持十进制运算。你有两个选择。
您可以将
.5
and转换1.5
为multiplication
anddivision
操作。但是由于输出将是 uint,您将有精度损失。前任:uint value = 5; uint lower_threshold = value / 2;//output 2 uint upper_threshold = value * 3 / 2;//output 7
您可以乘以
value
一些uint value
,以便执行value / 2
不会有任何精度损失。前任:uint value = 5; uint tempValue = value * 10;//output 50 uint lower_threshold = tempValue / 2;//output 25 uint upper_threshold = tempValue * 3 / 2;//output 75 if(tempValue >= lower_threshold && tempValue <= lower_threshold) { //do some stuff }
推荐阅读
- python - NLTK 无法导入特定语料库 (pl196x)
- python - 从“伪”HTML 中提取文本
- reactjs - 仅使用 css 和 tailwind 做出反应的可滚动表,最后 2 列固定在移动视图上
- azure-devops - 即使其中一项工作失败,如何将 azure devops 管道结果设置为成功
- python - 如何在数据框中获取定期时间间隔内的事件数
- javascript - 获取随机json得到第一个未定义然后结果
- python - 试图创建一个随机字母循环,但 python 错误
- c - 如果是字符串或整数,则检查回文输入
- pandas - Dask 数据帧 OutOfBoundsDatetime 错误
- bootstrap-4 -
'react-router-hash-link' 如何使用组件模拟 Scrollspy