root/trunk/src/tutorials/examples/ng/templ/templ.d

Revision 6, 1.2 kB (checked in by jcc7, 3 years ago)

Made more progress in developing convertToWiki and added some files.

Line 
1 /*
2
3     File:    template_d077.d
4     Author:  J C Calvarese, http://jcc_7.tripod.com/d/
5     Date:    2004/01/03 (updated 2005/11/01 to get it to compile with DMD 0.137)
6     Purpose: demonstrates using templates in D (using syntax introduced in DMD 0.77)
7     
8 */
9
10 template TStat(T)
11 { 
12    
13     T avg(T a, T b)
14     {
15         char[] s;
16         printf(s);
17         return (a + b) / 2;
18     }
19    
20     T avg(T a[])
21     {
22         T b;
23         b = 0;  /* If b isn't initialized, then "nan" will be returned. */
24        
25         for (int i = 0; i < a.length; i++)
26           b += a[i];
27        
28         return b / a.length;
29     }
30 }
31
32
33 void main()
34 { 
35     int i, j, avg1, avg2;
36     int m[];   
37     double avg3, avg4;
38     double d, e;
39     double n[];
40
41    
42     i = 6;
43     j = 8;
44    
45     m.length = 4;
46     m[0] = 2;
47     m[1] = 3;
48     m[2] = 4;
49     m[3] = 3;
50    
51     avg1 = TStat!(int).avg(i, j);
52     avg2 = TStat!(int).avg(m[]);
53
54     printf("avg1: %d\navg2: %d\n", avg1, avg2);
55    
56     d = 7.75;
57     e = 7.50;
58    
59     n.length = 3;
60     n[0] = 3.13;
61     n[1] = 3.15;
62     n[2] = 3.19;
63    
64     avg3 = TStat!(double).avg(d, e);
65     avg4 = TStat!(double).avg(n[]);
66        
67     printf("avg3: %lf\navg4: %lf\n", avg3, avg4);
68 }
Note: See TracBrowser for help on using the browser.