Soloway's recurring rainfall: Difference between revisions
Content added Content deleted
Drkameleon (talk | contribs) (added Arturo) |
(Created Nim solution.) |
||
Line 612: | Line 612: | ||
rainfall_problem() |
rainfall_problem() |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|Nim}}== |
|||
We catch exceptions related to wrong input, i.e. non integer values. Negative values are allowed. If an end of file is encountered, the program terminates with an error message. |
|||
<syntaxhighlight lang="Nim">import std/[strformat, strutils] |
|||
const EndValue = 99999 |
|||
var sum, count = 0.0 |
|||
while true: |
|||
var value: int |
|||
# Read input until a valid integer if found. |
|||
var input: string |
|||
while true: |
|||
stdout.write &"Enter an integer value, {EndValue} to terminate: " |
|||
stdout.flushFile() |
|||
try: |
|||
input = stdin.readLine() |
|||
value = input.parseInt() |
|||
break |
|||
except ValueError: |
|||
echo &"Expected an integer: got “{input}”" |
|||
except EOFError: |
|||
quit "\nEncountered end of file. Exiting.", QuitFailure |
|||
# Process value. |
|||
if value == EndValue: |
|||
echo "End of processing." |
|||
break |
|||
count += 1 |
|||
sum += value.toFloat |
|||
echo &" Current average is {sum / count}." |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
Sample session. |
|||
<pre>Enter an integer value, 99999 to terminate: 10 |
|||
Current average is 10.0. |
|||
Enter an integer value, 99999 to terminate: -20 |
|||
Current average is -5.0. |
|||
Enter an integer value, 99999 to terminate: 50 |
|||
Current average is 13.33333333333333. |
|||
Enter an integer value, 99999 to terminate: 3.5 |
|||
Expected an integer: got “3.5” |
|||
Enter an integer value, 99999 to terminate: aaa |
|||
Expected an integer: got “aaa” |
|||
Enter an integer value, 99999 to terminate: 10 |
|||
Current average is 12.5. |
|||
Enter an integer value, 99999 to terminate: 99999 |
|||
End of processing. |
|||
</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |