在 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 餘數 = 1;
  int a1、b1、a2、b2;
  vexcodeInit();
  a1=a2=20;
  b1 = b2 = 64;
  while(餘數 > 0){
    餘數 = a1 % b1;
    a1 = b1;
    b1 = 餘數;
  }
  Brain.Screen.printAt(5, 60, "GCD ( %d, %d ) = %d", a2, b2, a1);

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

使用使用者定義的函數:

int getGCD(int a, int b){
  int 餘數 = 1;
  while(餘數>0){
    餘數 = a % b;
    a = b;
    b = 餘數;
  }
  返回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() 的邏輯流程順序:

例:對一組數字求平均值

浮點 doAverage(int n1, int n2, int n3){
  浮點平均值 = (n1 + n2 + n3)/3;
  平均回報;
}

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

  n1=10; n2=20; n3=40;
  Brain.Screen.print(" %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(floattotalEnc, float vel){
  ();
  LeftMotor.setVelocity(50.0, 百分比);
LeftMotor.spinToPosition(totalEnc, deg, true); 返回; } int main() { int enc=1000; // >0:向前, <0:向後 vexcodeInit(); for(int i=0; i<10; i++){ enc *= -1; 直走(enc,100); Brain.Screen.printAt(5,60, "完成"); 報告運動值(); //這個延遲在這裡只是為了讓你查看這些動作。 //你不必在這裡設定延遲。 等待(2000,毫秒); } }

正如您所看到的,讓機器人以可變的次數前進和後退幾乎是不可能的;因為它只能在運行時確定。

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

Last Updated: