การเขียนฟังก์ชันเพื่อส่งกลับค่าใน VEXcode Pro V5

The VEX Visual Studio Code Extension has replaced VEXcode Pro V5, which is now end-of-life.

VEXcode Blocks and VEXcode Text remain actively developed and supported for all VEX platforms.

ตัวอย่าง: ฟังก์ชันหาตัวหารร่วมมาก (GCD) อย่างง่าย (โดยใช้อัลกอริทึมของยูคลิด)

ตัวอย่างต่อไปนี้ยังเป็นตัวอย่างวิธีการใช้ในโครงสร้างการวนซ้ำอย่างง่าย

โดยไม่ใช้ฟังก์ชันที่ผู้ใช้กำหนดเอง:

int main() { 
  int remainder = 1;
  int a1, b1, a2, b2;
  vexcodeInit();
  a1 = a2 = 20;
  b1 = b2 = 64;
  while(remainder > 0){
    remainder = a1 % b1;
    a1 = b1;
    b1 = remainder;
  }
  Brain.Screen.printAt(5, 60, "GCD ( %d, %d ) = %d", a2, b2, a1);

  a1 = a2 = 60;
  b1 = b2 = 200;
  while(remainder > 0){
    remainder = a1 % b1;
    a1 = b1;
    b1 = remainder;
  }
  Brain.Screen.printAt(5, 60, "GCD ( %d, %d ) = %d", a2, b2, a1);
}

การใช้ฟังก์ชันที่ผู้ใช้กำหนดเอง:

int getGCD(int a, int b){
  int remainder = 1;
  while(remainder>0){
    remainder = a % b;
    a = b;
    b = remainder;
  }
  return a;
}

int main() { 
  vexcodeInit();
  Brain.Screen.printAt(5, 60, "GCD ( %d, %d ) = %d",getGCD(20, 64));
  Brain.Screen.printAt(5, 60, "GCD ( %d, %d ) = %d",getGCD(60, 100));
}

วิดีโอด้านล่างแสดงลำดับการทำงานของตรรกะจากฟังก์ชันผู้เรียก main():

ตัวอย่าง: หาค่าเฉลี่ยของชุดตัวเลข

float doAverage(int n1, int n2, int n3){
  float avg = (n1 + n2 + n3)/3;
  return avg;
}

int main() { 
  int n1, n2, n3;
  Brain.Screen.print("average(%d, %d, %d) = %d", 10, 20, 30); 
  doAverage(10, 20, 30);

  n1=10; n2=20; n3=40;
  Brain.Screen.print("average(%d, %d, %d) = %d", n1, n2, n3);
  doAverage(n1, n2, n3);
}

ตัวอย่าง: เปิดใช้งานให้หุ่นยนต์เคลื่อนที่ไปข้างหน้าด้วยค่าตัวเข้ารหัสแบบแปรผัน

void reportMotionValues(){
  Brain.Screen.printAt(5,100, "%8.2lf%8.2lf%8.2f",
    LeftMotor.position(rev),
    LeftMotor.position(deg));
}

void goStraight(float totalEnc, float vel){
  LeftMotor.resetPosition();
  LeftMotor.setVelocity(50.0, percent);
  LeftMotor.spinToPosition(totalEnc, deg, true);
  return;
}

int main() { 
  int enc=1000; // >0: ไปข้างหน้า, <0: ถอยหลัง
  vexcodeInit();

  for(int i=0; i<10; i++){
    enc *= -1;
    goStraight(enc, 100);
    Brain.Screen.printAt(5,60, "Done");
    reportMotionValues();

    //การหน่วงเวลานี้มีไว้เพื่อให้คุณดูการกระทำเหล่านี้เท่านั้น
    //คุณไม่จำเป็นต้องใส่การหน่วงเวลาตรงนี้
    รอ (2000 มิลลิวินาที);
  }
}

อย่างที่คุณเห็น แทบจะเป็นไปไม่ได้เลยที่หุ่นยนต์จะเดินหน้าและถอยหลังด้วยจำนวนครั้งที่แตกต่างกัน เนื่องจากสามารถกำหนดได้เฉพาะที่รันไทม์เท่านั้น

For more information, help, and tips, check out the many resources at VEX Professional Development Plus

Last Updated: