【问题标题】:How do I convert a uint256 variable to an int256 one?如何将 uint256 变量转换为 int256 变量?
【发布时间】:2021-07-17 17:18:18
【问题描述】:

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

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;,但我想不通。

非常感谢您的反馈。

【问题讨论】:

    标签: solidity smartcontracts chainlink


    【解决方案1】:

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

    return int(timeStamp);
    

    注意:对于2^255-1int 最大值)和2^256-1(@987654327)之间的值,这将溢出(在 Solidity 0.7.x 和更早版本中)或引发异常(在 Solidity 0.8+ 中) @ 最大值)。但这很可能只是理论上的情况,因为预计时间戳不会有这么大的值。


    请注意,此行无法访问,因为您已经在上一行返回 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
    

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

    // note the multiple datatypes in the `returns` block
    function getThePriceAndTimestamp() public view returns (int, uint) {
        (
            uint80 roundID, 
            int price,
            uint startedAt,
            uint timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        return (price, timeStamp); // here returning multiple values
    }
    

    【讨论】:

    • 哦,顺便说一句,上面是不是意味着每个函数声明的 return 语句只能使用一次?
    • 您可以使用多个退货。在有条件的返回中有意义(例如:if(user.isActive == false) { return 0; } else { return user.score; })...只是在您的特定情况下,第二个将总是被忽略。
    猜你喜欢
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 2018-08-20
    • 2016-11-29
    • 2021-03-16
    • 2018-09-12
    • 2013-04-25
    相关资源
    最近更新 更多