在 VEXcode Pro V5 中编写返回一个值的函数

示例:一个简单的最大公分母(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() 的逻辑流序列:

示例:平均一组数值

loat 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: forward, <0: backward vexcodeInit(); for(int i=0; i<10; i++){ enc *= -1; goStraight(enc, 100); Brain.Screen.printAt(5,60, "Done"); reportMotionValues(); //this delay is here only for you to view these actions. //你不需要在这里设置一个延时。 wait(2000, msec); } }

如你所见,让机器人以可变次数前进和后退几乎是不可能的;因为它只能在运行时确定。

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