開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの機能制限無料版、light版)
- Script言語:Perl
『初めてのPerl 第6版』(Randal L. Schwartz, Tom Phoenix, brian d foy 共著、近藤 嘉雪 訳、オライリー・ジャパン、2012年、ISBN978-4-87311-567-2) の4章(サブルーチン)、4.12(練習問題)1を解いてみる。
その他参考書籍
1.
コード(TextWrangler)
sample.pl
#!/usr/bin/env perl use strict; use warnings; use utf8; use 5.016; binmode STDIN, ':utf8'; binmode STDOUT, ':utf8'; my @fred = qw{1 3 5 7 9}; my $fred_total = total(@fred); print "The total of \@fred is $fred_total.\n"; print "Enter some numbers on seprate lines: "; my $user_total = total(<STDIN>); print "The total of those numbers is $user_total.\n"; sub total{ my $result = 0; for(@_){ $result += $_; } return $result; }
入出力結果(Terminal)
$ ./sample.pl The total of @fred is 25. Enter some numbers on seprate lines: 1 2 3 4 5 6 7 8 9 10 The total of those numbers is 55. $
ちなみにJavaScriptの場合。
コード(TextWrangler)
function total(a){ var result = 0; for(var i = 0; i < a.length; i++){ result += a[i]; } return result; } var fred = [1,3,5,7,9]; var result = "The total of fred is " + total(fred) + ".\n"; var numbers = []; var str; while(1){ str = prompt("数値を入力(空文字で終了)",""); if(/^\s*$/.test(str)) break; if(! /^-?(\d+|\d+\.\d+)$/.test(str)){ alert("数値を入力してください!"); } numbers.push(parseFloat(str)); } result += "The total of those numbers(" + numbers.join(" ") + ") is " + total(numbers) + ".\n"; $('#pre0').text(result);
pythonの場合。
sample.py
コード(TextWrangler)
#!/usr/bin/env python3.3 #-*- coding:utf-8 -*- import re space = re.compile(r"^\s*$") pattern = re.compile(r"^(\d+|\d+\.\d+)$") def total(l): result = 0 for x in l: result += x return result fred = [1,3,5,7,9] print("The total of fred is {0}.".format(total(fred))) print("Enter some numbers on seprate lines") numbers = [] while True: str = input() if re.match(space, str): break if not re.match(pattern, str): print("Not a Number") continue numbers.append(float(str)) print("The total of those numbers is {0:g}.(ビルトイン関数sumで確認{1:g})".format(total(numbers), sum(numbers)))
入出力結果(Terminal)
$ ./sample.py The total of fred is 25. Enter some numbers on seprate lines 1 2 3 4 5 6 7 8 9 10 The total of those numbers is 55.(ビルトイン関数sumで確認55) $
0 コメント:
コメントを投稿