參考解答
這題是要模擬太空船的移動,並判斷太空船有在會被地雷或是黑洞吸引的範圍,每五步輸出太空船的位置。
讀檔之後,可以用 if-else
或者 switch-case
根據題目敘述判斷移動的方向,更改太空船的座標。太空船移動之後可能有兩種情況
和地雷的距離小於十單位
直接爆炸,用
break
跳出模擬移動的迴圈。因為題目說太空船爆炸之後可以忽略後面所有的指令,且不需要再印出太空船的位置。和黑洞的距離小於十單位
如果黑洞還沒消失(之前沒有碰過黑洞),則太空船被黑洞吸過去,位置變成黑洞的位置,黑洞消失。 如果黑洞已經消失了(之前有碰過黑洞),則不會發生任何事。
注意事項:
- 題目提到地雷的吸引力比黑洞還大,所以實作上要先判斷是不是離地雷很近,再判斷是不是離黑洞很近。
- 只要碰過一次黑洞,黑洞就會消失。所以可以用一個變數記錄之前是否有碰到黑洞。
- 每五步要輸出一次太空船的位置,可以用
n % 5
來判斷現在的步數是不是五的倍數。 - 如果剛好在五的倍數的步數碰到黑洞,要輸出的值是被黑洞吸過去的後的位置。
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 #include <stdio.h>
#include <stdlib.h> // for abs() function
int
main(){
int
x, y, z;
// location of spaceship
int
mx, my, mz, bx, by, bz;
// locations of mine and black hole
int
N;
// number of instructions
int
b = 0;
// a flag, indicating whether the spaceship has already encountered the black hole
// input
scanf
(
"%d%d%d"
, &x, &y, &z);
scanf
(
"%d%d%d %d%d%d"
, &mx, &my, &mz, &bx, &by, &bz);
scanf
(
"%d"
, &N);
// for each instruction
for
(
int
n = 1; n <= N; n++){
int
m;
scanf
(
"%d"
, &m);
// move spaceship according to the direction
if
(m == 1){
x++;
}
else
if
(m == 2){
x--;
}
else
if
(m == 3){
y++;
}
else
if
(m == 4){
y--;
}
else
if
(m == 5){
z++;
}
else
if
(m == 6){
z--;
}
// dist(spaceship, mine) < 10 : explode, don't need to perform the rest of the instructions
if
(
abs
(x - mx) +
abs
(y - my) +
abs
(z - mz) < 10){
break
;
}
// dist(spaceship, black hole) < 10 and hasn't encountered the black hole yet : attract by the black hole
else
if
(
abs
(x - bx) +
abs
(y - by) +
abs
(z - bz) < 10 && b == 0){
x = bx, y = by, z = bz;
b = 1;
}
// print the location every five steps
if
(n % 5 == 0){
printf
(
"%d %d %d\n"
, x, y, z);
}
}
return
0;
}