contract MatchTest{ function add(uint i,uint j) pure publicreturns(uint){ return i + j; } function sub(uint i,uint j) pure publicreturns(uint){ return i - j; } }
提示: • set(uint256 x):设置存储的整数值。 • get():返回当前存储的整数值 题目: 实现一个简单的计算器合约,支持加法、减法、乘法和除法操作。分别实现 add(uint256 a, uint256 b)、subtract(uint256 a, uint256 b)、multiply(uint256 a, uint256 b) 和 divide(uint256 a, uint256 b) 函数。 提示: add(uint256 a, uint256 b):返回 a 和 b 的和。 subtract(uint256 a, uint256 b):返回 a 和 b 的差。 multiply(uint256 a, uint256 b):返回 a 和 b 的积。 divide(uint256 a, uint256 b):返回 a 除以 b 的商,需检查 b 是否为零。
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0;
contract SimpleCalculator { // 加法函数 function add(uint256 a, uint256 b)public pure returns(uint256){ return a + b; }
// 减法函数 function subtract(uint256 a, uint256 b)public pure returns(uint256){ require(a >= b, "Subtraction would result in a negative value"); return a - b; }
// 乘法函数 function multiply(uint256 a, uint256 b)public pure returns(uint256){ return a * b; }
// 除法函数 function divide(uint256 a, uint256 b)public pure returns(uint256){ require(b != 0, "Cannot divide by zero"); return a / b; } }
// 出资函数,记录用户的贡献金额 function contribute()public payable { require(msg.value > 0, "Contribution must be greater than zero"); require(!goalReached, "Goal already reached");
// 提取资金函数,众筹达成目标后允许合约所有者提取资金 function withdraw()public{ require(msg.sender == owner, "Only the owner can withdraw funds"); require(goalReached, "Funding goal not reached");
// 存款函数,将用户发送的以太存入他们的账户 function deposit()public payable { require(msg.value > 0, "Deposit amount must be greater than zero"); balances[msg.sender] += msg.value; }
// 取款函数,用户可以提取指定金额的以太 function withdraw(uint256 amount)public{ require(amount > 0, "Withdrawal amount must be greater than zero"); require(balances[msg.sender] >= amount, "Insufficient balance");
// 存入资金并设置解锁时间 function deposit(uint256 unlockTime)public payable { require(msg.value > 0, "Deposit amount must be greater than zero"); require(unlockTime > block.timestamp, "Unlock time must be in the future");
// 提取资金,只有在解锁后才允许 function withdraw()public{ Deposit storage userDeposit = deposits[msg.sender]; require(block.timestamp >= userDeposit.unlockTime, "Funds are still locked"); require(userDeposit.amount > 0, "No funds to withdraw");