C Shell 脚本/Guppies
外观
#!/bin/csh
alias commas "echo \!:1 | sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta'"
# The program is to output a day-by-day account of the populations
# until one of them dies off or the end of the observation period is
# reached.
# All reproductions and deaths occur overnight.
# Any fractional fish are discarded.
# These sharks only feed during the day.
if ( $1 == 'default' ) then
set sharks = 54
set guppies = 1000
set duration = 150
else
printf "Please enter number of sharks: "
set sharks = $<
printf "Please enter number of guppies: "
set guppies = $<
printf "Number of days to observe: "
set duration = $<
endif
set day = 0
while ( $day < $duration )
@ day = $day + 1
#print
printf "Start of %3s Day: %15s sharks %15s guppies\n" $day `commas $sharks` `commas $guppies`
if ( $sharks <= 0 || $guppies <= 0 ) then
break
endif
# Each shark eats 5 guppies a day.
@ guppies_eaten = ( $sharks * 5 )
@ guppies = ( $guppies - $guppies_eaten )
if ( $guppies < 0 ) then
set guppies=0
endif
#print
printf "End of %5s Day: %15s sharks %15s guppies\n" $day `commas $sharks` `commas $guppies`
if ( $sharks <= 0 || $guppies <= 0 ) then
break
endif
# The guppies increase at a rate of 80% per day,
# provided the shark population is less than 20 % of the guppy population.
# Otherwise there is no increase in the guppy population.
if ( ( $guppies / $sharks ) > 5 ) then
@ guppy_plus = ($guppies * 80 ) / 100
@ guppies = ( $guppies + $guppy_plus )
endif
# The sharks increase at a rate of 5% of the guppy population per day,
# provided there are 50 or more guppies per shark.
# Otherwise, the sharks die off at a rate of 50% per day.
if ( ( $guppies / $sharks ) > 50 ) then
@ shark_increase = ( $guppies / 20 )
@ sharks = ( $sharks + $shark_increase )
else
@ sharks = ( $sharks / 2 )
endif
end
exit 0
- C shell 没有函数,因此所有逻辑都必须内联。可以使用“别名”来重用代码,例如使用“sed”程序对数字进行格式化(添加逗号)。
- 赋值给变量的数学表达式必须使用“@”符号而不是“set”关键字。
- 请注意,在控制语句方面,语法更接近于 BASIC 而不是 C 语言。在 “if” 语句表达式之后,必须包含关键字 “then”。
- Bourne shell 版本,由 Chris F.A. Johnson 提供,本版本源于此版本。
- 该程序的起源是家庭作业。