1

不得不问这个问题我感到非常愚蠢,但是我该如何处理返回值呢?

例如,我有这个代码:

int x = 0;

void setup(){
  Serial.begin(9600);
}

void loop(){
  int y = calc(x);
  Serial.println(y);

  delay(500);
}

int calc(int nmbr){
 int i = nmbr + 1;
 return i; 
}

我如何使它 x 上升?基本上,我想看到它变成 0、1、2、3、4、5 等等,我知道这很容易用 for() 完成,但我想知道如何处理返回值,而不是如何处理创建一个计数器。

解决方案可能很简单,当我看到它时我会捂脸,但过去 30 分钟我一直在看我的屏幕,我完全被困在这个问题上。

4

4 回答 4

2

你没有改变x,你正在改变另一个变量nmbr,因为你是x按值传递的,这是一个副本x,你可以通过引用传递它,或者因为x是全局的,你可以这样做:

int calc() {
 return x++;
}

但实际上,您应该只使用 for 循环 :)

int x;
for (x=0; x<10; x++) {
  Serial.println(x);
}
于 2012-10-25T11:46:35.550 回答
1

Mux的回答很好。我会添加更多的品种。首先,只需将函数返回值分配回x

loop() {
    x = calc( x );
    Serial.println( x );
}

其次,使用按引用调用,在其中传递一个指针x而不是x.

void loop() {
    int y = calc( &x );
    Serial.println( y );
}

int calc( int *nmbr ) {
    *nmbr++;
}

阅读“C 编程语言”以了解该语言及其可能性真的很有帮助。祝你好运 :-)

干杯,

于 2012-10-25T11:55:05.457 回答
0

尝试:

int y = 0;

void setup(){
  Serial.begin(9600);
}

void loop(){
  y = calc(y);
  Serial.println(y);

  delay(500);
}

int calc(int nmbr){
 int i = nmbr + 1;
 return i; 
}
于 2012-10-25T11:51:50.277 回答
0

您可以声明为静态 int ,而不是声明为 int 。

#include <stdio.h>


void func() {
    static int x = 0; // x is initialized only once across three calls of func() and x will get incremented three 
                          //times after all the three calls. i.e x will be 2 finally
    printf("%d\n", x); // outputs the value of x
    x = x + 1;
}

int main() { //int argc, char *argv[] inside the main is optional in the particular program
    func(); // prints 0
    func(); // prints 1
    func(); // prints 2
    return 0;
}
于 2014-01-09T07:44:20.200 回答