註解

當一個城市變得複雜時,註解可以幫助解釋程式的運行。但是註解要是沒有規律,反而會讓程式更混亂。

解釋部分程式

當部分程式需要被解釋時,就可以把單行註解 // comment 加在程式片段前

float binary_approx(float target_value, float leftbound, float rightbound, float epoch) {
    float guess_value;
    
    // try to guess a value for epoch times
    float guess_value;
    
    for (int i = 0; i < epoch; i++) {
        // choosing the guess value to the average of the bounds
        guess_value = (leftbound + rightbound) / 2.0;
        
        // if guessed lower than target, set leftbound to guess value
        if (guess_value < target_value) {
            leftbound = guess_value;
        }
        // if guessed higher than target, set rightbound to guess value
        else if (guess_value > target_value) {
            rightbound = guess_value;
        } 
        else {
            return guess_value;
        }
    }
    return guess_value;
}

Documentation

Documentation是一種統一的註解方式,擁有固定的語法。這種獨特的語法可以讓一些程式(例如Doxygen)生成程式紀錄。

Documenting functions

/**
 * Description of the function
 * 
 * @param [parameter name] first parameter name
 * @param [parameter name] second parameter name
 * @returns return value description
 */

範例:

/**
 * Binary approximation algorithm
 * 
 * @param target_value value to approximate
 * @param leftbound minimum bound
 * @param rightbound maximum bound
 * @param epoch maximum number of guesses
 * @returns approximated number
 */
float binary_approx(float target_value, float leftbound, float rightbound, float epoch) {
    float guess_value;
    
    for (int i = 0; i < epoch; i++) {
        guess_value = (leftbound + rightbound) / 2.0;
        
        if (guess_value < target_value) {
            leftbound = guess_value;
        }
        else if (guess_value > target_value) {
            rightbound = guess_value;
        } 
        else {
            return guess_value;
        }
    }
    return guess_value;
}

Documenting classes

範例:

/**
 * Chassis class
 *
 * A chassis capable of arcade, cheezy, and tank movement,
 * and include several autonomous movement functions.
 */
class Chassis {
    public:
        Chassis(std::vector<pros::Motor> left, std::vector<pros::Motor> right);
        void tank(float left_velocity, float right_velocity);
        void arcade(float throttle, float turn);
        void cheezy(float throttle, float turn);
        void move_distance(float distance);
        void turn_angle(float angle);
        void move_to_point(float x, float y);
    private:
        std::vector<pros::Motor> left;
        std::vector<pros::Motor> right;
};

Last updated