開発環境
- Microsoft Windows 8 Pro 64bit 日本語 (OS)
- Microsoft Visual Studio Express 2012 for Windows Desktop (IDE)
- プログラミング言語: C#
『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487311-294-7)の 第7章(C#のクラスとオブジェクト)7.10(練習問題)練習7-2を解いてみる。
その他参考書籍
練習7-2.
コード
using System;
class Math
{
public static double Add(double lhs, double rhs)
{
return lhs + rhs;
}
public static double Subtract(double lhs, double rhs)
{
return lhs - rhs;
}
public static double Multiply(double lhs, double rhs)
{
return lhs * rhs;
}
public static 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.add = function(lhs, rhs){
return lhs + rhs;
};
Math.subtract = function(lhs, rhs){
return lhs - rhs;
};
Math.multiply = function(lhs, rhs){
return lhs * rhs;
};
Math.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:
@staticmethod
def add(lhs, rhs):
return lhs + rhs
@staticmethod
def subtract(lhs, rhs):
return lhs - rhs
@staticmethod
def multiply(lhs, rhs):
return lhs * rhs
@staticmethod
def divide(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 $
メモ: pythonについて、statiemethodとclassmethodの違いの理解がいまいちまだ浅い感じ。。
0 コメント:
コメントを投稿