Box the compass: Difference between revisions

→‎Tcl: Added implementation
(→‎{{header|Python}}: Modulo already handles the negatives.)
(→‎Tcl: Added implementation)
Line 81:
32 North by west 354.37°
1 North 354.38°</pre>
 
=={{header|Tcl}}==
<lang tcl>proc angle2compass {angle} {
set dirs {
N NbE N-NE NEbN NE NEbE E-NE EbN E EbS E-SE SEbE SE SEbS S-SE SbE
S SbW S-SW SWbS SW SWbW W-SW WbS W WbN W-NW NWbW NW NWbN N-NW NbW
}
set unpack {N north E east W west S south b " by "}
 
# Compute the width of each compass segment
set sep [expr {360.0 / [llength $dirs]}]
 
# Work out which segment contains the compass angle
set dir [expr {round((fmod($angle + $sep/2, 360) - $sep/2) / $sep)}]
 
# Convert to a named direction
return [string totitle [string map $unpack [lindex $dirs $dir]]]
}
 
for {set i 0} {$i < 33} {incr i} {
set heading [expr {$i * 11.25}]
if {$i % 3 == 1} {set heading [expr {$heading + 5.62}]}
if {$i % 3 == 2} {set heading [expr {$heading - 5.62}]}
set index [expr {$i % 32 + 1}]
puts [format "%2i %-18s %7.2f°" $index [angle2compass $heading] $heading]
}</lang>
Output:
<pre>
1 North 0.00°
2 North by east 16.87°
3 North-northeast 16.88°
4 Northeast by north 33.75°
5 Northeast 50.62°
6 Northeast by east 50.63°
7 East-northeast 67.50°
8 East by north 84.37°
9 East 84.38°
10 East by south 101.25°
11 East-southeast 118.12°
12 Southeast by east 118.13°
13 Southeast 135.00°
14 Southeast by south 151.87°
15 South-southeast 151.88°
16 South by east 168.75°
17 South 185.62°
18 South by west 185.63°
19 South-southwest 202.50°
20 Southwest by south 219.37°
21 Southwest 219.38°
22 Southwest by west 236.25°
23 West-southwest 253.12°
24 West by south 253.13°
25 West 270.00°
26 West by north 286.87°
27 West-northwest 286.88°
28 Northwest by west 303.75°
29 Northwest 320.62°
30 Northwest by north 320.63°
31 North-northwest 337.50°
32 North by west 354.37°
1 North 354.38°
</pre>
Anonymous user