Программирование LEGO NXT роботов на языке NXC - Управляющие структуры — различия между версиями

Материал из roboforum.ru Wiki
Перейти к: навигация, поиск
(Управляющие структуры)
(Оператор "if")
Строка 5: Строка 5:
  
 
==Оператор "if"==
 
==Оператор "if"==
Sometimes you want that a particular part of your program is only executed in certain situations. In this case the
+
Иногда возникает необходимость выполнять какую-то часть программы только в какой-то ситуации. В этом случае используется оператор "if". Давайте я вам покажу как это делается на примере. Для этого мы добавим новый трюк в программу, с которой мы работали в предыдущей главе. Мы хотим, чтобы робот проезжал прямо, а потом поворачивал случайным образом либо вправо, либо влево. Чтоб добиться такого поведения от робота мы опять будем использовать случайные числа. Мы берём случайное число, которое либо положительное, либо отрицательное. Если это число меньше 0 мы делаем поворот направо, иначе поворот налево. Вот получившаяся программа:
if statement is used. Let me give an example. We will again change the program we have been working with so
 
far, but with a new twist. We want the robot to drive along a straight line and then either make a left or a right
 
turn. To do this we need random numbers again. We pick a random number that is either positive or negative. If
 
the number is less than 0 we make a right turn; otherwise we make a left turn. Here is the program:
 
  
 
  #define MOVE_TIME 500
 
  #define MOVE_TIME 500

Версия 09:33, 17 мая 2009

Автор: Daniele Benedettelli

Перевод: © Ботов Антон aka =DeaD=, 2009

Эксклюзивно для www.roboforum.ru
копирование на другие ресурсы и публикация перевода
без разрешения его автора запрещены

Управляющие структуры

В предыдущих главах мы видели операторы "repeat" и "while". Эти операторы управляют тем, каким образом выполняются или не выполняются другие операторы программы. Такие операторы называются “управляющие структуры”. В этой главе мы познакомимся с другими управляющими структурами.

Оператор "if"

Иногда возникает необходимость выполнять какую-то часть программы только в какой-то ситуации. В этом случае используется оператор "if". Давайте я вам покажу как это делается на примере. Для этого мы добавим новый трюк в программу, с которой мы работали в предыдущей главе. Мы хотим, чтобы робот проезжал прямо, а потом поворачивал случайным образом либо вправо, либо влево. Чтоб добиться такого поведения от робота мы опять будем использовать случайные числа. Мы берём случайное число, которое либо положительное, либо отрицательное. Если это число меньше 0 мы делаем поворот направо, иначе поворот налево. Вот получившаяся программа:

#define MOVE_TIME 500
#define TURN_TIME 360
task main()
{
  while(true)
  {
    OnFwd(OUT_AC, 75);
    Wait(MOVE_TIME);
    if (Random() >= 0)
    {
      OnRev(OUT_C, 75);
    }
    else
    {
      OnRev(OUT_A, 75);
    }
    Wait(TURN_TIME);
  }
}

The if statement looks a bit like the while statement. If the condition between the parentheses is true the part between the brackets is executed. Otherwise, the part between the brackets after the word else is executed. Let us look a bit better at the condition we use. It reads Random() >= 0. This means that Random() must be greater-than or equal to 0 to make the condition true. You can compare values in different ways. Here are the most important ones:

== equal to
< smaller than
<= smaller than or equal to
> larger than
>= larger than or equal to
!= not equal to

You can combine conditions use &&, which means “and”, or ||, which means “or”. Here are some examples of conditions:

true always true
false never true
ttt != 3 true when ttt is not equal to 3
(ttt >= 5) && (ttt <= 10) true when ttt lies between 5 and 10
(aaa == 10) || (bbb == 10)true if either aaa or bbb (or both) are equal to 10

Note that the if statement has two parts. The part immediately after the condition, which is executed when the condition is true, and the part after the else, which is executed when the condition is false. The keyword else and the part after it are optional. So you can omit them if there is nothing to do when the condition is false.

Оператор "do"

There is another control structure, the do statement. It has the following form: do { statements; } while (condition); The statements between the brackets after the do part are executed as long as the condition is true. The condition has the same form as in the if statement described above. Here is an example of a program. The robot runs around randomly for 20 seconds and then stops. int move_time, turn_time, total_time; task main() { total_time = 0; do { move_time = Random(1000); turn_time = Random(1000); OnFwd(OUT_AC, 75); Wait(move_time); OnRev(OUT_C, 75); Wait(turn_time); total_time += move_time; total_time += turn_time; } while (total_time < 20000); Off(OUT_AC); } Note also that the do statement behaves almost the same as the while statement. But in the while statement the condition is tested before executing the statements, while in the do statement the condition is tested at the end. For the while statement, the statements might never be executed, but for the do statement they are executed at least once. Summary In this chapter we have seen two new control structures: the if statement and the do statement. Together with the repeat statement and the while statement they are the statements that control the way in which the program is executed. It is very important that you understand what they do. So better try some more examples yourself before continuing.