Sdut Object-Oriented Programming Practice 2 (function template)
Object-Oriented Programming machine Exercise 2 (function template) Time Limit: 1000 MS Memory limit: 65536 K The topic description uses arrays and function templates to calculate the maximum number of five numbers (considering integers, single precision, and long integers respectively ). Enter five int integers, five float integers, and five long integers. The output outputs the maximum values of five int integers, the maximum values of five float integers, and the maximum values of five long integers. Sample Input
11 22 666 44 5511.11 22.22 33.33 888.88 55.551234567 222222 333333 444444 555555
Sample output
666888.881234567
Using function templates for the same question is much easier than using function overloading.
The code is both readable and concise ..
# Include
Using namespace std; // template declaration. T is the type parameter template.
// Define a general function. Use T as the virtual type name T max (T a []) {int I; T m = 0; for (I = 0; I <5; I ++) {if (a [I]> m) m = a [I];} return m ;}// main function int main () {int I; int x [5], X; float y [5], Y; long z [5], Z; // input for (I = 0; I <5; I ++) cin> x [I]; for (I = 0; I <5; I ++) cin> y [I]; for (I = 0; I <5; I ++) cin> z [I]; // template call X = max (x); Y = max (y ); Z = max (z); // output cout <X <endl; cout <Y <endl; cout <Z <endl; return 0 ;}