2013-02-14 7 views
1

例如说我要进入这个代码整块到一个命令:谈到的代码的整体结构成一条线用C

int k = 0; 

for (k = 0; k < 50; k++) 
{ 
    sprintf(buf, "M LR 10 -10\n");      //We put the string "M L 10" into the string buffer. 
    write(sock, buf, strlen(buf));      //We send the buffer into the socket. 
    memset(buf, 0, 80);        //Clear the buffer, set buffer to value 0. 
    read(sock, buf, 80);        //Read from the socket to get the results. 
    int lme, rme; 
    sprintf(buf, "S MELR\n");       //sensor command to find ME values 
    write(sock, buf, strlen(buf));      //sends the buffer to the socket 
    memset(buf, 0, 80);        //Clear the buffer, set buffer to value 0. 
    read(sock, buf, 80);        //read from socket to get results. 
    sscanf(buf, "S MELR %i %i\n", &lme, &rme);   //takes lme and rme values from results 
    printf(buf, "%3i %-4i\n", lme, rme); 
    //distance = 2 * (22/7) * r 
} 

for (k = 50; k < 51; k++) 
{ 
    sprintf(buf, "C RME\n");       //We put the string "C RME" into the string buffer to reset. 
    write(sock, buf, strlen(buf));      //We send the buffer into the socket. 
    memset(buf, 0, 80);        //Clear the buffer, set buffer to value 0. 
    read(sock, buf, 80);        //Read from the socket to get the results. 
} 

,使我只是改变{sprintf(buf, "M LR 10 -10\n");}字符串的值即10-10,其余的过程会自行执行:

例如,set_motor_speed(10 -10\n)在主代码中会执行整个功能,该怎么做呢?

+1

这是一个_really_基本问题,的排序更好地解决一个基本的编程教科书比在线问答网站。你在C中寻找的术语是“函数定义”,但如果你还不知道,那么你可能根本不应该用C语言编写代码 - 对于初学者来说,它太低级了。 – zwol 2013-02-14 14:30:09

+0

如果只有C中有一种方式来反复执行某个'函数... ....呃,那只是一个管道梦。 – 2013-02-14 14:30:22

+1

有时候我们甚至想要一个函数*不能被一次又一次地调用... – 2013-02-14 14:32:38

回答

5

正如其他人说:你可以读到这样的事情在C语言的书,但嘿,我们是很好的:

set_motor_speed(int a, int b) { 
    ... 
    for(k = 0; k < 50; k++) { 
     sprintf(buf, "M LR %i %i\n", a, b); 
     ... 
    } 
    ... 
} 

set_motor_speed(10, -10); 
set_motor_speed(5, -5);