M M E E K K
I I
Writing Writing Methods Methods
in C# in C#
204111 Computer & Programming
Dr.Arnon Rungsawang
http://mike.cpe.ku.ac.th/204111
M M E E in C# in C# I I K K 204111 Computer & - - PowerPoint PPT Presentation
Writing Writing Methods Methods M M E E in C# in C# I I K K 204111 Computer & Programming Dr.Arnon Rungsawang http://mike.cpe.ku.ac.th/204111 2 K K 204111 Computer & Programming - Writing Methods I I E M M E
204111 Computer & Programming
Dr.Arnon Rungsawang
http://mike.cpe.ku.ac.th/204111
204111 Computer & Programming - Writing Methods
2
Version 2008/1
M M E E
K K I I
204111 Computer & Programming - Writing Methods
3
Version 2008/1
M M E E
K K I I
static void myHello() { // method body Console.WriteLine(“Hello World!”) } class HelloWorld { public static void Main () { myHello(); } … }
204111 Computer & Programming - Writing Methods
4
Version 2008/1
M M E E
K K I I
classes, e.g.,
– Console – MessageBox – Int32 – Math
properties:
– methods, e.g.,
– data properties, e.g.,
204111 Computer & Programming - Writing Methods
5
Version 2008/1
M M E E
K K I I
method’ ’s name s name should provide a well-defined, easy-to- understand functionality.
– A method takes input (parameters) takes input (parameters), performs some actions performs some actions, and (sometime) returns a value returns a value.
Console class:
Console.WriteLine ( “The ultimate conflict begins...”); class method Information provided to the method (parameters or called “arguments”) dot
204111 Computer & Programming - Writing Methods
6
Version 2008/1
M M E E
K K I I
Me tho d De sc r iptio n E xample Abs( x ) absolute value of x Abs( 23.7 ) is 23.7 Abs( 0 ) is 0 Abs( -23.7 ) is 23.7 Ceiling( x ) rounds x to the smallest integer not less than x Ceiling( 9.2 ) is 10.0 Ceiling( -9.8 ) is -9.0 Cos( x ) trigonometric cosine of x (x in radians) Cos( 0.0 ) is 1.0 Exp( x ) exponential method ex Exp( 1.0 ) is approximately 2.7182818284590451 Exp( 2.0 ) is approximately 7.3890560989306504 Floor( x ) rounds x to the largest integer not greater than x Floor( 9.2 ) is 9.0 Floor( -9.8 ) is -10.0 Log( x ) natural logarithm of x (base e) Log( 2.7182818284590451 ) is approximately 1.0 Log( 7.3890560989306504 ) is approximately 2.0 Max( x, y ) larger value of x and y (also has versions for float, int and long values) Max( 2.3, 12.7 ) is 12.7 Max( -2.3, -12.7 ) is -2.3 Min( x, y ) smaller value of x and y (also has versions for float, int and long values) Min( 2.3, 12.7 ) is 2.3 Min( -2.3, -12.7 ) is -12.7 Pow( x, y ) x raised to power y (xy) Pow( 2.0, 7.0 ) is 128.0 Pow( 9.0, .5 ) is 3.0 Sin( x ) trigonometric sine of x (x in radians) Sin( 0.0 ) is 0.0 Sqrt( x ) square root of x Sqrt( 900.0 ) is 30.0 Sqrt( 9.0 ) is 3.0 Tan( x ) trigonometric tangent of x (x in radians) Tan( 0.0 ) is 0.0 Co mmo nly use d Math c lass me tho ds.
204111 Computer & Programming - Writing Methods
7
Version 2008/1
M M E E
K K I I
– A method is abstract in that we don't really have to think about its internal details in order to use it.
works in order to invoke it.
– Easier to reuse – Easier to understand – – Divide and conquer Divide and conquer
204111 Computer & Programming - Writing Methods
8
Version 2008/1
M M E E
K K I I
method method name name return return type type parameter list parameter list The parameter list specifies the type The parameter list specifies the type and name of and name of each each parameter. parameter. The name of a parameter in the method The name of a parameter in the method declaration is called a declaration is called a formal argument, formal argument,
formal parameter. class MyClass {
static int SquareSum( int num1, int num2 )
… properties properties
method header
204111 Computer & Programming - Writing Methods
9
Version 2008/1
M M E E
K K I I
static int SquareSum(int num1, int num2) { // method body int sum = num1 + num2; return sum * sum; } class MyClass { … … }
method body
204111 Computer & Programming - Writing Methods
10
Version 2008/1
M M E E
K K I I
– Its expression must conform to the return type.
static int SquareSum(int num1, int num2) { // method body int sum = num1 + num2; return (sum * sum); } class MyClass { … … } return int
204111 Computer & Programming - Writing Methods
11
Version 2008/1
M M E E
K K I I
actual arguments in the invocation are copied copied into the formal arguments formal arguments.
static int SquareSum (int num1, int num2) { int sum = num1 + num2; return sum * sum; } int num = SquareSum (2, 3); See SquareSum.cs
Caller in Caller in Main( ) Main( )
204111 Computer & Programming - Writing Methods
12
Version 2008/1
M M E E
K K I I
String.Format( “{0:C}”, 2.0 )
204111 Computer & Programming - Writing Methods
13
Version 2008/1
M M E E
K K I I
– The Show Show method we will use has four parameters
Argument 4: MessageBox Icon (Optional) Argument 3: OK dialog
Argument 2: Title bar string (Optional) Argument 1: Message to display
204111 Computer & Programming - Writing Methods
14
Version 2008/1
M M E E
K K I I
1 // Sum.cs 2 // Summation with the for structure. 3 4 using System; 5 using System.Windows.Forms; 6 7 class Sum 8 { 9 static void Main( string[] args ) 10 { 11 int sum = 0; 12 13 for ( int number = 2; number <= 100; number += 2 ) 14 sum += number; 15 16 MessageBox.Show( "The sum is " + sum, 17 "Sum Even Integers from 2 to 100", 18 MessageBoxButtons.OK, 19 MessageBoxIcon.Information ); 20 21 } // end method Main 22 23 } // end class Sum
Argument 4: MessageBox Icon (Optional) Argument 3: OK dialog
Argument 2: Title bar string (Optional) Argument 1: Message to display
204111 Computer & Programming - Writing Methods
15
Version 2008/1
M M E E
K K I I
Me ssageBo x B uttons Desc riptio n MessageBoxButton.OK
Specifies that the dialog should include an OK button.
MessageBoxButton.OKCancel
Specifies that the dialog should include OK and Cancel buttons. Warns the user about some condition and allows the user to either continue
MessageBoxButton.YesNo
Specifies that the dialog should contain Yes and No buttons. Used to ask the user a question.
MessageBoxButton.YesNoCancel
Specifies that the dialog should contain Yes, No and Cancel buttons. Typically used to ask the user a question but still allows the user to cancel the operation.
MessageBoxButton.RetryCancel
Specifies that the dialog should contain Retry and Cancel buttons. Typically used to inform a user about a failed operation and allow the user to retry or cancel the operation.
MessageBoxButton.AbortRetryIgnore Specifies that the dialog should contain Abort,
Retry and Ignore buttons. Typically used to inform the user that one of a series of operations has failed and allow the user to abort the series of
the failed operation and continue.
Buttons fo r message dialo gs.
204111 Computer & Programming - Writing Methods
16
Version 2008/1
M M E E
K K I I
Me ssage Bo x I c o ns I c o n De sc riptio n MessageBoxIcon.Exclamation Displays a dialog with an exclamation point. Typically used to caution the user against potential problems. MessageBoxIcon.Information Displays a dialog with an informational message to the user. MessageBoxIcon.Question Displays a dialog with a question
user a question. MessageBoxIcon.Error Displays a dialog with an x in a red circle. Helps alert user of errors or important messages. I c o ns fo r me ssage dialo gs.
204111 Computer & Programming - Writing Methods
17
Version 2008/1
M M E E
K K I I
1 // Interest.cs 2 // Calculating compound interest, using MessageBox and Pow. 3 4 using System; 5 using System.Windows.Forms; 6 7 class Interest 8 { 9 static void Main( string[] args ) 10 { 11 decimal amount, principal = ( decimal ) 1000.00; 12 double rate = .05; 13 string output; 14 15
16 17 for ( int year = 1; year <= 10; year++ ) 18 { 19 amount = principal * 20 ( decimal ) Math.Pow( 1.0 + rate, year ); 21 22
23 String.Format( "{0:C}", amount ) + "\n"; 24 } 25 26 MessageBox.Show( output, 27 "Compound Interest", 27 MessageBoxButtons.OK, 28 MessageBoxIcon.Information ); 29 } // end method Main 30 } // end class Interest
204111 Computer & Programming - Writing Methods
18
Version 2008/1
M M E E
K K I I
A brief introduction to make you feel comfortable about using such methods. We will explore the full glory later.
204111 Computer & Programming - Writing Methods
19
Version 2008/1
M M E E
K K I I
– Eg., all math related methods are defined in the Math Math class.
– To make a method static, a programmer applies the static modifier modifier to the method definition. – The result of each invocation of a class (static) method is completely determined by the actual parameters actual parameters.
204111 Computer & Programming - Writing Methods
20
Version 2008/1
M M E E
K K I I
keep (internal) state (internal) state after each call.
– A computer may generate a sequence of random numbers using the following formula: Xn = 75 Xn-1 mod (231 – 1) – To write a method called GetNextRandom() we have to give the method the previous number: int GetNextRandom( ) { return 75 * previous % ( 231 – 1 ); } – Method created without without a static modifier is called an “instance method instance method”.
204111 Computer & Programming - Writing Methods
21
Version 2008/1
M M E E
K K I I
using System; class myRandom { int previous; myRandom() { this.previous=1;} //constructor myRandom(int s) { this.previous=s;} //constructor int GetNextRandom() // instance method instance method { int now = (int)(Math.Pow(7,5) * this.previous % (Math.Pow(2,31)-1)); this.previous=now; return now; } public static void Main() { myRandom a = new new myRandom(5); // instance creation myRandom b = new new myRandom(50); while (true) { Console.WriteLine("{0} {1}", a.GetNextRandom(), b.GetNextRandom()); Console.ReadLine(); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
204111 Computer & Programming - Writing Methods
22
Version 2008/1
M M E E
K K I I
Object a previous= 5 myRandom a = new myRandom(5); Object b previous= 50 myRandom b = new myRandom(50); a.GetNextRandom(); Object a previous= 84035 a.GetNextRandom(); Object a previous= 1412376245 b.GetNextRandom(); Object b previous= 840350 b.GetNextRandom(); Object b previous= 1238860568
204111 Computer & Programming - Writing Methods
23
Version 2008/1
M M E E
K K I I
– the dog concept, the house concept, …
– An instance of a concept, e.g., the dog at my home. – An object has internal state
encapsulation.
– Thus the action (method) may depend on depend on both parameters parameters and internal state internal state. myRandom(int s) { this.previous=s;} //constructor int GetNextRandom() // instance method instance method { int now = (int)(Math.Pow(7,5) * this.previous % (Math.Pow(2,31)-1)); this.previous=now; return now; }
204111 Computer & Programming - Writing Methods
24
Version 2008/1
M M E E
K K I I
Random myRandom; myRandom = new Random();
This calls the This calls the Random Random constructor constructor, which is , which is a special method that sets up the object a special method that sets up the object
– An object is an instance instance of a particular class.
Random generator1 = new Random(); int num = generate1.Next();
204111 Computer & Programming - Writing Methods
25
Version 2008/1
M M E E
K K I I
Random Random ()
Random methods
int Next ()
// returns an integer from 0 to Int32.MaxValue
int Next (int max)
// returns an integer from 0 upto but not including max
int Next (int min, int max)
// returns an integer from min upto but not including max
double NextDouble ( )
// returns a double number from 0 to 1
See RandomNumbers.cs
204111 Computer & Programming - Writing Methods
26
Version 2008/1
M M E E
K K I I
204111 Computer & Programming - Writing Methods
27
Version 2008/1
M M E E
K K I I
– hard to read and understand, – hard to debug, – hard to improve or update.
– should be divided into several sub-programs, each has its own clear duty. – has some parts that must be performed repeatedly.
class Atm { } void Main() { … ; … ; }
204111 Computer & Programming - Writing Methods
28
Version 2008/1
M M E E
K K I I
Start ATM Check pin code Service menu withdraw balance? deposit more service Stop
…
204111 Computer & Programming - Writing Methods
29
Version 2008/1
M M E E
K K I I
– Divide program into several parts. – Write each part with a new method. – Each method has its own clear duty to perform. – Call each method in Main(), or we can call a method inside a method?
class Atm { } void Main() { withdraw(); deposit(); balance(); } withdraw() { } deposit() { } balance() { } etc() { }
204111 Computer & Programming - Writing Methods
30
Version 2008/1
M M E E
K K I I
– Console, Math, MessageBox, …
– Readability – Maintainability – Reusability
204111 Computer & Programming - Writing Methods
31
Version 2008/1
M M E E
K K I I
Console.WriteLine(“Hello World!”); Send string “Hello World” to standard output. int x = int.Parse(Console.ReadLine()); Get string from standard input and send to int.Parse() to convert that string into integer and keep result in variable x. Console.WriteLine(“{ 0} ! = { 1} ”, n, fac(n)); Call method fac() with argument n and send the result to standard output. if IsPrime(x) res + = x; Call method IsPrime with x.
204111 Computer & Programming - Writing Methods
32
Version 2008/1
M M E E
K K I I
– Abs(x) : absolute value – Pow(x,y) : xy – Sqrt(x) : square root – Log(x) : natural log (base e) – Exp(x) : ex – Sin(x) : trigonometric sine – Cos(x) : trigonometric cosine – Tan(x) : trigonometric tangent – PI : π – E : e – …
Click to see Math member at msdn.
204111 Computer & Programming - Writing Methods
33
Version 2008/1
M M E E
K K I I
.NET Framework Class Library Math.Cos Method
Return the cosine of the specified angle. C# Public static double Cos (double d); Param eters d An angle, measured in radian. Return Value The cosine of d. Rem arks The angle, d, must be in radians. Multiply by n/ 180 to convert degrees to radians. Exam ple …
Click to see Math.Cos at msdn.
204111 Computer & Programming - Writing Methods
34
Version 2008/1
M M E E
K K I I
– Find angle (in degrees) between the two vectors.
– Both vector begin from the origin (0,0). – Get both vectors from stdin: (ux,uy) and (vx,vy). – Calculate the angle between them from – Output the result to stdout.
⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + + + =
− 2 2 2 2 1
cos
y x y x y y x x
v v u u v u v u θ
(ux,uy) (vx,vy) θ (0,0)
204111 Computer & Programming - Writing Methods
35
Version 2008/1
M M E E
K K I I
⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + + + =
2 2 2 2
) cos(
y x y x y y x x
v v u u v u v u θ
… double cosine= (Ux* Vx+ Uy* Vy)/ ((length(Ux,Uy)* length(Vx,Vy)); double degree= Math.Acos(cosine)* 180/ Math.PI; … public static double length(double x, double y) { return Math.Sqrt(x* x+ y* y); }
204111 Computer & Programming - Writing Methods
36
Version 2008/1
M M E E
K K I I
using System; class AngleBetweenTwoVectors { public static void Main() { double Ux, Uy, Vx, Vy; Ux= ReadInput("Ux"); Uy= ReadInput("Uy"); Vx= ReadInput("Vx"); Vy= ReadInput("Vy"); double cosine = (Ux* Vx + Uy* Vy)/ (length(Ux,Uy) * length(Vx,Vy)); double degree = Math.Acos(cosine) * 180 / Math.PI; Console.WriteLine("Angle between the two vectors is [ { 0} ] .", degree); Console.ReadLine(); } static double ReadInput(string s) / / method ReadInput() { Console.Write("Please enter { 0} : ", s); return Double.Parse(Console.ReadLine()); } static double length(double x, double y) / / method length() { return Math.Sqrt(Math.Pow(x,2) + Math.Pow(y,2); } }
click
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
204111 Computer & Programming - Writing Methods
37
Version 2008/1
M M E E
K K I I
– tell us how to use the method. – consists of the method property, data type of the result when finished, method name, and parameters it needs.
– Declaration of local variables. – Method statements (can call another method inside a method). – Return something to the caller.
static double length(double x, double y) / / method length() { return Math.Sqrt(Math.Pow(x,2) + Math.Pow(y,2); } 1 2 3 4
204111 Computer & Programming - Writing Methods
38
Version 2008/1
M M E E
K K I I
static double length(double x, double y) / / method length() { return Math.Sqrt(Math.Pow(x,2) + Math.Pow(y,2); }
method property return data type method name parameters method body Return to the caller with the same type of data as declared in the method header method header
204111 Computer & Programming - Writing Methods
39
Version 2008/1
M M E E
K K I I
static int max(int a, int b) int res= max(35, 47); static string toString(int i, int radix) string s= toString(10, 16); static void gc() gc();
If that method returns something, we always found it inside another method or on the right side of assignment
int x= int.Parse(Console.ReadLine());
204111 Computer & Programming - Writing Methods
40
Version 2008/1
M M E E
K K I I
– Begin with letter or ‘_’ – Can be composed of letter, digit, and ‘_’ – Case sensitive – Cannot use reserve word reserve word as method name – In general, the first letter is lower case. – In general, the method name is verb.
– fillCircle, turnLeft, launchRocket, fireTopedo
204111 Computer & Programming - Writing Methods
41
Version 2008/1
M M E E
K K I I
static void turnLeft(double angle) static bool launchRocket(double speed, string destination) static string readString()
204111 Computer & Programming - Writing Methods
42
Version 2008/1
M M E E
K K I I
using System; class readInt { static void Main() { Console.WriteLine("OUTPUT: { 0} ", readInt()); Console.ReadLine(); } static int readInt() { int x= 0; / / local variable bool success= false; / / local variable do { try { Console.Write(“Type something”); x= int.Parse(Console.ReadLine()); success= true; } catch (Exception e) { Console.WriteLine(e.Message); success= false; } } while (!success); return x; / / return to the caller at line 4 } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
click
204111 Computer & Programming - Writing Methods
43
Version 2008/1
M M E E
K K I I
return command will bring back the execution to the caller.
– The only one data that can be returned must have the same data type as declared in the header. – When nothing returns, we can just write “return();” – The last statement in the method body can act as an implicit return implicit return, when we have nothing to return to the caller.
static void printSomething(string name) { Console.Write(“Hello, ”); Console.WriteLine(“{ 0} !”, name); } static long clip(long a) { if (a> 0) return a; else return 0; / / 0 is promoted to 0L }
204111 Computer & Programming - Writing Methods
44
Version 2008/1
M M E E
K K I I
– within the method body, – within the block it has been declared, or block that is found inside the outer block, – after it has been declared.
static void test(int a) { int z= 7; { int x= z; Console.WriteLine(x); } Console.WriteLine(x); / / wrong { Console.WriteLine(x); / / wrong int x= z; Console.WriteLine(x); { int y= z; Console.WriteLine(y); } { int x= z; Console.WriteLine(x); } / / wrong } } 1 2 3 4 5 6 7 8 9 10 11
204111 Computer & Programming - Writing Methods
45
Version 2008/1
M M E E
K K I I
– is created at the point where it is declared, but without any implicit intialization. – is destroyed when the block is finished.
local variables.
class A { static void Main(string [ ] args) { int s= 0, n= int.Parse(Console.ReadLine()); for(int i= 0; i< = n; i+ + ) { int i2= i* i; s+ = i2; int i3= i2* i; s+ = i3; } Console.WriteLine(s); } } 1 2 3 4 5 6 7 8 9 10 11 12 s,n i i2 i3
204111 Computer & Programming - Writing Methods
46
Version 2008/1
M M E E
K K I I
public static printSomething(string msg) { Console.WriteLine(msg); } public static int myAbs(int n) { if (a< 0) a= -a; } public static float myMax(float x, y) { return (x> y)?x: y; } public static double length(double x, double y) { double x= Math.Abs(x); return Math.Sqrt(x* x + y* y); } public static float getBlackColor() { return 0.0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
204111 Computer & Programming - Writing Methods
47
Version 2008/1
M M E E
K K I I
int a, b; … b = power ( a+ 2 , 3 ); … public static int power (int x , int y ) { int p = 1; for (int i= 1; i< = y; i+ + ) p * = x; return p ; }
204111 Computer & Programming - Writing Methods
48
Version 2008/1
M M E E
K K I I
public static float max(float x, float y) { … } x= max( (float) (a/ 3.0), 1f ); y= max( Float.Parse(str), 1 ); / / 1 -> 1.0f x= max( (float) (a/ 2) ); / / wrong number of args y= max( “1.0”, 1 ); / / cannot promote “1.0” to 1f
not ok
204111 Computer & Programming - Writing Methods
49
Version 2008/1
M M E E
K K I I
public static float max(float x, float y) { … } double x = max( 1.0f , (int) (x/ 3) ); int y = (int) max( 1 , 2 ); float z = max( max(x,y) , 10.5f ); long x = max( 4.0f , 2.3f ); / / float to long float y= max( 4.0 , 1.0 ); / / double to float max( 2.0f , 1.0f ); / / max return float
not ok
204111 Computer & Programming - Writing Methods
50
Version 2008/1
M M E E
K K I I
n a b h − =
= − +
≈
n i i i b a
x x f h dx x f
1 1
) 2 ( . ) (
x0 x1 x2 xn f(x)
204111 Computer & Programming - Writing Methods
51
Version 2008/1
M M E E
K K I I
using System; class Integration { public static void Main() { Console.WriteLine(midPoint(1.0, 3.0, 1000)); Console.ReadLine(); } static double midPoint(double a, double b, int n) { double h, x, area= 0.0; h= (b-a)/ n; x= a+ h/ 2.0; for (int i= 1; i< = n; i+ + ) { area+ = h* f(x); x+ = h; } return area; } static double f(double x) { / / f(x) = 2* x^ 2 return 2* x* x; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
x0 x1x2 xn f(x)
n a b h − =
= − +
≈
n i i i b a
x x f h dx x f
1 1
) 2 ( . ) (
204111 Computer & Programming - Writing Methods
52
Version 2008/1
M M E E
K K I I
n a b h − =
x0 x1 x2 xn f(x)
⎟ ⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + ⎟ ⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + + ⎟ ⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + + ≈
− = − =
) ( ) ( 2 ) ( 4 ) ( 3 ) (
2 ,... 6 , 4 , 2 1 ,... 5 , 3 , 1
b f ih a f ih a f a f h dx x f
n i n i b a
204111 Computer & Programming - Writing Methods
53
Version 2008/1
M M E E
K K I I
static double simpson(double a, double b, int n) { double s1, s2, x, h= (b-a)/ n; s1= s2= 0.0; x= a; for (int i= 1; i< = n; i+ + ) { x+ = h; if (i% 2= = 1) / / is odd? s1+ = f(x); else s2+ = f(x); } return (h/ 3 * (f(a)+ (4* s1)+ (2* s2)+ f(b))); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 n a b h − =
x0 x1 x2 xn f(x)
⎟ ⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + ⎟ ⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + + ⎟ ⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + + ≈
− = − =
) ( ) ( 2 ) ( 4 ) ( 3 ) (
2 ,... 6 , 4 , 2 1 ,... 5 , 3 , 1
b f ih a f ih a f a f h dx x f
n i n i b a
click
204111 Computer & Programming - Writing Methods
54
Version 2008/1
M M E E
K K I I
switch on the circuit.
) 1 ( 5 . 5 . t t
− − − −
= dt t I t Q ) ( ) (
C t Q t V ) ( ) ( =
V(t) C
204111 Computer & Programming - Writing Methods
55
Version 2008/1
M M E E
K K I I
public static void Main() { double c= 0.05; / / capacitor 0.05 farad double v, q; / / voltage and charge double a= 1.0, b= 10.0; / / 1 to 10 seconds for (double t= 1; t< = b; t+ + ) { q= simpson(a, t, 1000); v= q/ c; Console.WriteLine("t= { 0} \ tq= { 1} \ tv= { 2} ", t, q, v); } } static double simpson(double a, double b, int n) { … ; } static double f(double t) { double y= 4* (1-Math.Exp(-0.5)); y* = Math.Exp(-0.5* (t-1)); return y* (1-Math.Exp(-t)); }
) 1 ( ) 1 ( 4 ) (
) 1 ( 5 . 5 . t t
e e e t I
− − − −
− − =
∫
= dt t I t Q ) ( ) (
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 V(t) C
C t Q t V ) ( ) ( =
click
204111 Computer & Programming - Writing Methods
56
Version 2008/1
M M E E
K K I I
static int max(int x, int y) { return (x> y)?x: y; } static double max(double x, double y) { return (x< y)?y: x; } static int max(int a, int b, int c) { if (x> y & x> z) return x; else if (y> x & y> z) return y; else return z; } 1 2 3 4 5 6 7 8 9 10 11
204111 Computer & Programming - Writing Methods
57
Version 2008/1
M M E E
K K I I
parameter list, but return the different data type.
sameness and the difference difference of the parameter list are not considered from the variable’s names used in that parameter list.
static int max(int x, int y) { if (x> y) return x; else return y; } static double max(double x, double y) { if (x> y) return x; else return y; } static int max(int a, int b) { if (a> b) return a; else return b; } 1 2 3 4 5 6 7 8 9 not ok
204111 Computer & Programming - Writing Methods
58
Version 2008/1
M M E E
K K I I
using System; class myPrint { static void Print(int i) { Console.WriteLine("{0}", i+""); } static void Print(float i) { Console.WriteLine("{0}", i+""); } static void Print(double i) { Console.WriteLine("{0}", i+""); } static void Print(char i) { Console.WriteLine("{0}", i+""); } // ... some more codes public static void Main() { Print(2); Print(2.0f); Print(2/1.0); Print('a'); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22