对int,char*,int *,double类型的两个数据进行比较
3条回答 默认 最新
关注 模板: int Compare(T a, U b) { if (a>b) { return 1; } if (a == b) { return 0; } if (a < b) return -1; }
测试代码:
#include<stdlib.h> #include<iostream> #include<string> #include<vector> using namespace std; template<class T,class U> int Compare(T a, U b) { if (a>b) { return 1; } if (a == b) { return 0; } if (a < b) return -1; } void MInt() { int a = 3; int b = 5; if (Compare<int, int>(a, b) ==0) cout << "a == b" << endl; else if (Compare<int, int>(a, b) > 0) { cout << "a > b" << endl; } else if (Compare<int, int>(a, b) < 0) cout << "a < b" << endl; } void MDouble() { double a = 4.0; double b = 5.0; if (Compare<double, double>(a, b) == 0) cout << "a == b" << endl; else if (Compare<double, double>(a, b) > 0) { cout << "a > b" << endl; } else if (Compare<double, double>(a, b) < 0) cout << "a < b" << endl; } void _MInt() { int * a = new int; *a = 3; int *b = new int; *b = 5; if (Compare<int*, int*>(a, b) == 0) cout << "a == b" << endl; else if (Compare<int*, int*>(a, b) > 0) { cout << "a > b" << endl; } else if (Compare<int*, int*>(a, b) < 0) cout << "a < b" << endl; } void _MDouble() { double *a = new double; *a = 3.0; double *b = new double; *b = 5.0; *b = 5; if (Compare<double*, double*>(a, b) == 0) cout << "a == b" << endl; else if (Compare<double*, double*>(a, b) > 0) { cout << "a > b" << endl; } else if (Compare<double*, double*>(a, b) < 0) cout << "a < b" << endl; } int main() { MInt(); MDouble(); _MInt(); _MDouble(); system("pause"); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报