此外,您的函数没有返回值,这会给您一个错误。看起来你在混淆事情。要么将其声明为 void,要么返回声明类型的值(最后是您的分配所要求的)。无论哪种方式,都需要调用函数或方法来执行,而您没有调用它!所以你的函数里面的代码没有运行!!以下:
void imAMethod()
{
println("hello");
}
这是一个有效的方法,但什么都不做,你需要调用它,比如:
imAMethod();// calling your method
void imAMethod()
{
println("hello");
}
但这也不起作用,会给你错误“看起来你正在混合“活动”和“静态”模式”。那是因为要在处理中使用一个函数,你需要在草图中至少有一个 setup() 方法,所以:
void setup()
{
imAMethod();
}//end of setup
void imAMethod()
{
println("hello");
}
将按预期工作。
但是您需要一个函数,因此正如 Jesper 指出的那样,您必须执行以下操作:
int a = 30; // those are global variables to pass to your function
int b = 20;
void setup()// this is a builtin basic Processing method
{
//call your function
println("The sum of " + a + " and " + b + " is "+ twoNumbers(a, b));
}
int twoNumbers(int a, int b)
{
//do your math and tests here
return result;
}
作业中还有一件事不清楚。一个函数必须返回一些东西,所以不清楚如果a不大于b函数应该返回什么。您将不得不处理这种情况,否则编译器会抱怨。您可能希望将此测试移出函数以使事情变得更容易,例如:
if (a < b)
println("The sum of " + a + " and " + b + " is "+ twoNumbers(a, b));//call your function
else
println(a + " is smaller than " + b);
在函数中只做总和。但这可能不是作业所要求的......无论如何,即使a不大于b ,您也需要返回一些东西。请注意,打印到控制台也可以在函数内部完成。
Hummm, re reading the assignment a think what is expected is: Aways return the sum, and just print if a is greater than b, which makes more sense and is easier, something like:
int twoNUmbers(int a, int b)
{
if (a < b){/*print the string*/}
return a + b;
}
Just a note for jlordo. In Processing.org you don't have a main, or better, it is transparent/hidden from user. Processing is like a "dialect" of java. So the code above would run as it is. There are two basic builtin functions: setup() and draw(). If the user do not use none of them the IDE will warps it in a setup() function, that will call the main() somewhere else. It will run once. Draw() instead loops forever.