Loading... # 1 ```C++ #include <iostream> using namespace std; template<typename T> T find_max(T arr[], int size) { T max_elem = arr[0]; for (int i = 1; i < size; i++) { if (arr[i] > max_elem) { max_elem = arr[i]; } } return max_elem; } template<typename T> T find_min(T arr[], int size) { T min_elem = arr[0]; for (int i = 1; i < size; i++) { if (arr[i] < min_elem) { min_elem = arr[i]; } } return min_elem; } int main() { // Test int array int int_arr[] = { 3, 6, 2, 9, 4 }; int int_size = sizeof(int_arr) / sizeof(int); int max_int = find_max(int_arr, int_size); int min_int = find_min(int_arr, int_size); cout << "Max int: " << max_int << endl; cout << "Min int: " << min_int << endl; // Test double array double double_arr[] = { 3.5, 6.1, 2.8, 9.7, 4.2 }; int double_size = sizeof(double_arr) / sizeof(double); double max_double = find_max(double_arr, double_size); double min_double = find_min(double_arr, double_size); cout << "Max double: " << max_double << endl; cout << "Min double: " << min_double << endl; return 0; } ``` 下面是该程序的输出结果: ```C++ Max int: 9 Min int: 2 Max double: 9.7 Min double: 2.8 ``` # 2 ```C++ #include <iostream> #include <math.h> using namespace std; double Sq(double x) { if (x < 0) { throw x; } return sqrt(x); } int main() { double input; cout << "Enter a number: "; cin >> input; try { double result = Sq(input); cout << "Square root of " << input << " is " << result << endl; } catch (double x) { cout << "Error: Cannot calculate square root of a negative number." << endl; } return 0; } ``` 下面是该程序的一些测试数据及输出结果: ```C++ Enter a number: 25 Square root of 25 is 5 ``` ```C++ Enter a number: -16 Error: Cannot calculate square root of a negative number. ``` ```C++ Enter a number: 0 Square root of 0 is 0 ``` 最后修改:2023 年 08 月 05 日 © 允许规范转载 赞 如果觉得我的文章对你有用,请随意赞赏