微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将 uint256 变量转换为 int256 变量?

如何解决如何将 uint256 变量转换为 int256 变量?

我试图通过在此代码uint timeStamp 正下方键入 return timeStamp; 来打印 return price;

pragma solidity ^0.6.7;

import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";

contract PriceConsumerV3 {

AggregatorV3Interface internal priceFeed;

/**
 * Network: Kovan
 * Aggregator: BTC/USD
 * Address: 0x6135b13325bfC4B00278B4abC5e20bbce2D6580e
 */
constructor() public {
    priceFeed = AggregatorV3Interface(0x6135b13325bfC4B00278B4abC5e20bbce2D6580e);
}

/**
 * Returns the latest price
 */
function getThePrice() public view returns (int) {
    (
        uint80 roundID,int price,uint startedAt,uint timeStamp,uint80 answeredInRound
    ) = priceFeed.latestRoundData();
    return price;
    return timeStamp;
}
}

当我在 Remix Compiler 上编译上面的代码时,它回复

TypeError:返回参数类型 uint256 不能隐式转换为预期类型(第一个返回变量的类型)int256。返回时间戳; ^-------^

我倾向于认为我只需要输入 int256 return timeStamp 或类似的东西而不是 return timeStamp;,但我无法弄清楚。

感谢反馈。

解决方法

您可以使用以下语法将 uint 类型转换为 int

return int(timeStamp);

注意:对于 2^255-1int 最大值)和 {{ 1}}(2^256-1 最大值)。但这很可能只是一个理论案例,因为预计时间戳不会有这么大的值。


请注意,此行无法访问,因为您已经在上一行返回了 uint

price

如果要返回多个值,可以使用以下语法:

(
    uint80 roundID,int price,uint startedAt,uint timeStamp,uint80 answeredInRound
) = priceFeed.latestRoundData();
return price; // the `price` is returned,and the function doesn't execute after this line
return timeStamp; // this is ignored because of the early return on previous line

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。