2012年11月22日木曜日

開発環境

『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487311-294-7)の 第7章(C#のクラスとオブジェクト)7.10(練習問題)練習7-1を解いてみる。

その他参考書籍

練習7-1.

コード

using System;

class Math
{
    public double Add(double lhs, double rhs)
    {
        return lhs + rhs;
    }
    public double Subtract(double lhs, double rhs)
    {
        return lhs - rhs;
    }
    public double Multiply(double lhs, double rhs)
    {
        return lhs * rhs;
    }
    public double Divide(double lhs, double rhs)
    {
        return lhs / rhs;
    }
}
class Tester
{
    public void Run()
    {
        Math math = new Math();
        int x = 10;
        int y = 20;
        Console.WriteLine("x = {0}, y = {1}", x, y);
        Console.WriteLine("和: " + math.Add(x, y));
        Console.WriteLine("差: " + math.Subtract(x, y));
        Console.WriteLine("積: " + math.Multiply(x, y));
        Console.WriteLine("商: " + math.Divide(x, y));
    }
    static void Main()
    {
        Tester t = new Tester();
        t.Run();
    }
}

入出力結果(Console Window)

x = 10, y = 20
和: 30
差: -10
積: 200
商: 0.5
続行するには何かキーを押してください . . .

ちなみにJavaScriptの場合。

コード(TextWrangler)

var Math = function(){};
Math.prototype.add = function(lhs, rhs){
  return lhs + rhs;
};
Math.prototype.subtract = function(lhs, rhs){
  return lhs - rhs;
};
Math.prototype.multiply = function(lhs, rhs){
  return lhs * rhs;
};
Math.prototype.divide = function(lhs, rhs){
  return lhs / rhs;
};
var x = 10, y = 20;
var math = new Math();
var funcs = {"和":math.add, "差":math.subtract, "積":math.multiply, "商":math.divide}
var a = ["和", "差", "積", "商"];
var result = "x = " + x + ", y = " + y + "\n";
for(var i = 0; i < a.length; i++){
  result += a[i] + ": " + funcs[a[i]](x,y) + "\n";
}
$('#pre0').text(result);



pythonの場合。

sample.py

コード(TextWrangler)

#!/usr/bin/env python3.3
#-*- coding utf-8 -*-

class Math:
    def add(self, lhs, rhs):
        return lhs + rhs
    
    def subtract(self, lhs, rhs):
        return lhs - rhs
    
    def multiply(self, lhs, rhs):
        return lhs * rhs
    
    def divide(self, lhs, rhs):
        return lhs / rhs

math = Math()
x = 10
y = 20
print("x = {0}, y = {1}".format(x, y))
funcs = {"和":math.add, "差":math.subtract, "積":math.multiply, "商":math.divide}
for i in ["和", "差", "積", "商"]:
    print("{0}: {1}".format(i, funcs[i](x,y)))

入出力結果(Terminal)

$ ./sample.py
x = 10, y = 20
和: 30
差: -10
積: 200
商: 0.5
$

0 コメント:

コメントを投稿