Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

C Shell Scripting/Guppies

From Wikibooks, open books for an open world
<C Shell Scripting

Source code

[edit |edit source]


#!/bin/cshaliascommas"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')thensetsharks=54setguppies=1000setduration=150elseprintf"Please enter number of sharks: "setsharks=$<printf"Please enter number of guppies: "setguppies=$<printf"Number of days to observe: "setduration=$<endifsetday=0while($day<$duration)@day=$day+1#printprintf"Start of %3s Day: %15s sharks  %15s guppies\n"$day`commas$sharks``commas$guppies`if($sharks<=0||$guppies<=0)thenbreakendif# Each shark eats 5 guppies a day.@guppies_eaten=($sharks*5)@guppies=($guppies-$guppies_eaten)if($guppies<0)thensetguppies=0endif#printprintf"End of %5s Day: %15s sharks  %15s guppies\n"$day`commas$sharks``commas$guppies`if($sharks<=0||$guppies<=0)thenbreakendif# 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)endifendexit0


Lessons

[edit |edit source]
  1. C shell does not have functions so all logic must be in-lined. An "alias" can be created to reuse code such as formating a number with commas using the "sed" program.
  2. Mathematical expression that are assigned to variable must with the "@" sign instead of the keyword "set".
  3. Notice that the syntax is closer to BASIC than the C language with regards to control statements. You must include the key word "then" after the "if" statement expression.

Notes

[edit |edit source]
Retrieved from "https://en.wikibooks.org/w/index.php?title=C_Shell_Scripting/Guppies&oldid=3676737"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp