我怎样才能稳定地添加多个输入?

How can I add up multiple inputs in solidity?

这个测试合约是执行一个数学函数。所需的输入之一是“单位”。我需要编写一个函数,然后总结所有输入的单位。我该怎么做?

下面是我的代码。

 pragma solidity ^0.8.0;
    
    contract GpCalculator{
    
        string CourseName;
        uint Unit;
        uint Score;
    
    struct Details{
        string CourseName;
        uint Unit;
        uint Score;
        }
     
    Details[] public details;

//function that request for the input

function addCourseDetails(string memory _CourseName, uint _Unit, uint _Score)public{
    details.push(Details(CourseName = _CourseName, Unit = _Unit, Score = _Score));
    }


//functions that allows the user view their last input

function retrieveDetails()public view returns(string memory, uint, uint){
    return(CourseName, Unit, Score);}

//function that grades the performance of the user, based on their input score

function retrieveGrade() public view returns(string memory){
    if (Score >69 && Score<=100){
        return("A");
        } else if (Score >59 && Score<=69){
            return ("B");
            } else if (Score >49 && Score<=59){
                return ("C");
                }else if (Score >45 && Score<=49){
                    return ("D");
                    }else if (Score <45 && Score >=30){
                        return ("E");
                        }else if(Score <30){
                            return ("Retake this course!");
                            }else {
                        return ("Imposible");
                    }
    
//function that calculates Grade point

function calculatePoint()public view returns(uint G){
    if (Score >69 && Score <=100){
        G = 4;
    }else if (Score >59 && Score<=69){
        G = 3;
    }else if (Score >49 && Score<=59){
        G = 2;
    }else if (Score >45 && Score<=49){
        G = 1;
    }else if (Score <=44){
        G = 0;
    }else{
        G = 0;
    }
    return(Unit * G);
    }


}

最终公式预计为===所有成绩点总和/所有单元总和。

非常感谢您的回答。

您可以创建一个 view 函数来循环遍历 details 数组并对其项求和。

只要使用 call 调用视图函数而不是作为 transaction 的一部分(例如从另一个使用事务调用的函数)。

function getUnitSum() public view returns (uint) {
    // default value 0
    uint sum;

    for (uint i = 0; i < details.length; i++) {
        sum += details[i].Unit;
    }

    return sum;
}