⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 m2

📁 unix v7是最后一个广泛发布的研究型UNIX版本
💻
📖 第 1 页 / 共 2 页
字号:
if (j <= k)	do i = j, k  {		_ _ _	}.P2but this has to be a conscious act,and is often overlooked by programmers..PPA more serious problem with the.UC DOstatementis that it encourages that a program be writtenin terms of an arithmetic progressionwith small positive steps,even though that may not be the best way to write it.If code has to be contorted to fit the requirementsimposed by the Fortran.UC DO ,it is that much harder to write and understand..PPTo overcome these difficulties,Ratforprovides a.UL whilestatement,which is simply a loop:``while some condition is true,repeat this group of statements''.It hasno preconceptions about why one is looping.For example, this routine to compute sin(x)by the Maclaurin seriescombines two termination criteria..P1 1.ta .3i .6i .9i 1.2i 1.5i 1.8ireal function sin(x, e)	# returns sin(x) to accuracy e, by	# sin(x) = x - x**3/3! + x**5/5! - ...	sin = x	term = x	i = 3	while (abs(term)>e & i<100) {		term = -term * x**2 / float(i*(i-1))		sin = sin + term		i = i + 2	}	return	end.P2.PPNotice thatif the routine is entered with.UL termalready smaller than.UL e ,the loop will be done.ulzero times,that is, no attempt will be made to compute.UL x**3and thus a potential underflow is avoided.Since the test is made at the top of a.UL whileloopinstead of the bottom,a special case disappears _the code works at one of its boundaries.(The test.UL i<100is the other boundary _making sure the routine stops aftersome maximum number of iterations.).PPAs an aside, a sharp character ``#'' in a linemarks the beginning of a comment;the rest of the line is comment.Comments and code can co-exist on the same line _one can make marginal remarks,which is not possible with Fortran's ``C in column 1'' convention.Blank lines are also permitted anywhere(they are not in Fortran);they should be used to emphasize the natural divisionsof a program..PPThe syntax of the .UL whilestatement is.P1while (\fIlegal Fortran condition\fP)	\fIRatfor statement\fP.P2As with the.UL if ,.ullegal Fortran conditionis something that can go intoa Fortran Logical.UC IF ,and.ulRatfor statementis a single statement,which may be multiple statements in braces..PPThe.UL whileencourages a style of coding not normallypracticed by Fortran programmers.For example, suppose.UL nextchis a function which returns the next input characterboth as a function value and in its argument.Then a loop to find the first non-blank character is just.P1while (nextch(ich) == iblank)	;.P2A semicolon by itself is a null statement,which is necessary here to mark the end of the.UL while ;if it were not present, the.UL whilewould control the next statement.When the loop is broken, .UL ichcontains the first non-blank.Of course the same code can be written in Fortran as.P1 1100	if (nextch(ich) .eq. iblank) goto 100.P2but many Fortran programmers (and a few compilers) believe this line is illegal.The language at one's disposalstrongly influences how one thinks about a problem..sp.SHThe ``for'' Statement.PPThe.UL forstatementis another Ratfor loop, whichattempts to carry the separation ofloop-body from reason-for-loopinga step furtherthan the.UL while.A.UL forstatement allows explicit initializationand increment steps as part of the statement.For example, a.UC DOloop is just.P1for (i = 1; i <= n; i = i + 1) ....P2This is equivalent to.P1i = 1while (i <= n) {	...	i = i + 1}.P2The initialization and increment of.UL ihave been moved into the.UL forstatement,making it easier to see at a glancewhat controls the loop..PPThe.UL forand.UL whileversions have the advantage that they will be done zero timesif.UL nis less than 1; this is not true of the.UL do ..PPThe loop of the sine routine in the previous sectioncan be re-writtenwith a.UL foras.P1 3for (i=3; abs(term) > e & i < 100; i=i+2) {	term = -term * x**2 / float(i*(i-1))	sin = sin + term}.P2.PPThe syntax of the.UL forstatement is.P1for ( \fIinit\fP ; \fIcondition\fP ; \fIincrement\fP )	\fIRatfor statement\fP.P2.ulinitis any single Fortran statement, which gets done oncebefore the loop begins..ulincrementis any single Fortran statement,which gets done at the end of each pass through the loop,before the test..ulconditionis again anything that is legal in a logical .UC IF.Any of .ulinit,.ulcondition,and.ulincrementmay be omitted,although the semicolons.ulmustalways be present.A non-existent.ulconditionis treated as always true,so.UL "for(;;)"is an indefinite repeat.(But see the.UL repeat-untilin the next section.).PPThe.UL forstatement is particularlyuseful forbackward loops, chaining along lists,loops that might be done zero times,and similar things which are hard to express with a .UC DOstatement,and obscure to write out with.UC IF 'sand.UC GOTO 's.For example,here is abackwards.UC DOloopto find the last non-blank character on a card:.P1for (i = 80; i > 0; i = i - 1)	if (card(i) != blank)		break.P2(``!='' is the same as .UC ``.NE.'' ).The code scans the columns from 80 through to 1.If a non-blank is found, the loopis immediately broken..UL break \& (and.UL nextwork in.UL for 'sand.UL while  'sjust as in .UL do 's).If .UL ireaches zero,the card is all blank..PPThis code is rather nasty to write with a regular Fortran.UC DO ,since the loop must go forward,and we must explicitly set up proper conditionswhen we fall out of the loop.(Forgetting this is a common error.)Thus:.P1 1.ta .3i .6i .9i 1.2i 1.5i 1.8i	DO 10 J = 1, 80		I = 81 - J		IF (CARD(I) .NE. BLANK) GO TO 1110	CONTINUE	I = 011	....P2The version that uses the.UL forhandles the termination condition properly for free;.UL i.uliszero when we fall out of the.UL forloop..PPThe incrementin a.UL forneed not be an arithmetic progression;the following program walks along a list(stored in an integer array.UL ptr )until a zero pointer is found,adding up elements from a parallel array of values:.P1sum = 0.0for (i = first; i > 0; i = ptr(i))	sum = sum + value(i).P2Notice that the code works correctly if the list is empty.Again, placing the test at the top of a loopinstead of the bottom eliminates a potential boundary error..SHThe ``repeat-until'' statement.PPIn spite of the dire warnings,there are times when one really needs a loop that tests at the bottomafter one pass through.This service is provided by the.UL repeat-until :.P1repeat	\fIRatfor statement\fPuntil (\fIlegal Fortran condition\fP).P2The.ulRatfor statementpart is done once,then the condition is evaluated.If it is true, the loop is exited;if it is false, another pass is made..PPThe.UL untilpart is optional, so a bare.UL repeatis the cleanest way to specify an infinite loop.Of course such a loop must ultimately be broken by sometransfer of control such as.UL stop ,.UL return ,or.UL break ,or an implicit stop such as running out of input witha.UC READstatement..PPAs a matter of observed fact[8], the.UL repeat-untilstatement is.ulmuchless used than the other looping constructions;in particular, it is typically outnumbered ten to one by.UL forand.UL while .Be cautious about using it, for loops that test only at thebottom often don't handle null cases well..SHMore on break and next.PP.UL breakexits immediately from .UL do ,.UL while ,.UL for ,and.UL repeat-until ..UL nextgoes to the test part of.UL do ,.UL whileand.UL repeat-until ,and to the increment step of a.UL for ..SH``return'' Statement.PPThe standard Fortran mechanism for returning a value from a function uses the name of the function as a variable which can be assigned to;the last value stored in it is the function value upon return.For example, here is a routine.UL equalwhich returns 1 if two arrays are identical,and zero if they differ.The array ends are marked by the special value \-1..P1 1.ta .3i .6i .9i 1.2i 1.5i 1.8i# equal _ compare str1 to str2;#	return 1 if equal, 0 if not	integer function equal(str1, str2)	integer str1(100), str2(100)	integer i	for (i = 1; str1(i) == str2(i); i = i + 1)		if (str1(i) == -1) {			equal = 1			return		}	equal = 0	return	end.P2.PPIn many languages (e.g., PL/I)one instead says.P1return (\fIexpression\fP).P2to return a value from a function.Since this is often clearer, Ratfor provides such a.UL returnstatement _in a function.UL F ,.UL return (expression)is equivalent to.P1{ F = expression; return }.P2For example, here is.UL equalagain:.P1 1.ta .3i .6i .9i 1.2i 1.5i 1.8i# equal _ compare str1 to str2;#	return 1 if equal, 0 if not	integer function equal(str1, str2)	integer str1(100), str2(100)	integer i	for (i = 1; str1(i) == str2(i); i = i + 1)		if (str1(i) == -1)			return(1)	return(0)	end.P2If there is no parenthesized expression after.UL return ,a normal.UC RETURN is made.(Another version of.UL equalis presented shortly.).sp.SHCosmetics.PPAs we said above,the visual appearance of a languagehas a substantial effecton how easy it is to read and understandprograms.Accordingly, Ratfor provides a number of cosmetic facilitieswhich may be used to make programs more readable..SHFree-form Input.PPStatements can be placed anywhere on a line;long statements are continued automatically,as are long conditions in.UL if ,.UL while ,.UL for ,and.UL until .Blank lines are ignored.Multiple statements may appear on one line,if they are separated by semicolons.No semicolon is needed at the end of a line,ifRatforcan make some reasonable guess about whether the statementends there.Lines ending with any of the characters.P1=    +    -    *    ,    |    &    (    \(ru.P2are assumed to be continued on the next line.Underscores are discarded wherever they occur;all others remain as part of the statement..PPAny statement that begins with an all-numeric field isassumed to be a Fortran label,and placed in columns 1-5 upon output.Thus.P1write(6, 100); 100 format("hello").P2is converted into.P1	write(6, 100)100	format(5hhello).P2.SHTranslation Services.PPText enclosed in matching single or double quotesis converted to.UL nH...but is otherwise unaltered(except for formatting _ it may get split across card boundariesduring the reformatting process).Within quoted strings, the backslash `\e' serves as an escape character:the next character is taken literally.This provides a way to get quotes (and of course the backslash itself) intoquoted strings:.P1"\e\e\e\(fm".P2is a string containing a backslash and an apostrophe.(This is.ulnotthe standard convention of doubled quotes,but it is easier to use and more general.).PPAny line that begins with the character `%'is left absolutely unaltered  except for stripping off the `%'and moving the line one position to the left.This is useful for inserting control cards,and other things that should not be transmogrified(like an existing Fortran program).Use `%' only for ordinary statements,not for the condition parts of.UL if ,.UL while ,etc., or the output may come out in an unexpected place..PPThe following character translations are made, except within single or double quotesor on a line beginning with a `%'..P1.ta .5i 1.5i 2i==	.eq.	!=	.ne.>	.gt.	>=	.ge.<	.lt.	<=	.le.&	.and.	|	.or.!	.not.	^	.not..P2In addition, the following translations are providedfor input devices with restricted character sets..P1.ta .5i 1.5i 2i[	{	]	}$(	{	$)	}.P2.SH``define'' Statement.PPAny string of alphanumeric characters can be defined as a name;thereafter, whenever that name occurs in the input(delimited by non-alphanumerics)it is replaced by the rest of the definition line.(Comments and trailing white spaces are stripped off).A defined name can be arbitrarily long,and must begin with a letter..PP.UL defineis typically used to create symbolic parameters:.P1define	ROWS	100define	COLS	50.if t .sp 5pdimension a(ROWS), b(ROWS, COLS).if t .sp 5p	if (i > ROWS  \(or  j > COLS) ....P2Alternately, definitions may be written as.P1define(ROWS, 100).P2In this case, the defining text is everything after the comma up to the balancingright parenthesis;this allows multi-line definitions..PPIt is generally a wise practice to use symbolic parametersfor most constants, to help make clear the function of whatwould otherwise be mysterious numbers.As an example, here is the routine.UL equal again, this time with symbolic constants..P1 3.ta .3i .6i .9i 1.2i 1.5i 1.8idefine	YES		1define	NO		0define	EOS		-1define	ARB		100# equal _ compare str1 to str2;#	return YES if equal, NO if not	integer function equal(str1, str2)	integer str1(ARB), str2(ARB)	integer i	for (i = 1; str1(i) == str2(i); i = i + 1)		if (str1(i) == EOS)			return(YES)	return(NO)	end.P2.SH``include'' Statement.PPThe statement.P1	include file.P2inserts the filefound on input stream.ulfileinto theRatforinput in place of the.UL includestatement.The standard usage is to place .UC COMMONblocks on a file,and.UL includethat file whenever a copy is needed:.P1subroutine x	include commonblocks	...	endsuroutine y	include commonblocks	...	end.P2This ensures that all copies of the .UC COMMONblocks are identical.SHPitfalls, Botches, Blemishes and other Failings.PPRatfor catches certain syntax errors, such as missing braces,.UL elseclauses without an.UL if ,and most errors involving missing parentheses in statements.Beyond that, since Ratfor knows no Fortran, any errors you make will be reported by the Fortran compiler,so you will from time to time have to relate a Fortran diagnostic backto the Ratfor source..PPKeywords are reserved _using.UL if ,.UL else ,etc., as variable names will typically wreak havoc.Don't leave spaces in keywords.Don't use the Arithmetic.UC IF ..PPThe Fortran.UL nHconvention is not recognized anywhere by Ratfor;use quotes instead.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -