如何将整数转换为 double ?我有这段代码,它的结果是 15
,而不是 15.45
那是因为程序将第一个数字作为结果的类型,在这个程序中是整数
#include <iostream>
using namespace std;
template < class T1 , class T2 >
T1 smaller ( T1 a, T2 b ){
return (a<b?a:b);
}
int main(){
int x = 98;
double y = 15.45;
cout << smaller( x , y ) << endl;
return 0;
}
最佳答案
这是因为您的返回类型是根据第一个输入参数的类型模板化的,在本例中是整数。
您应该为输入和输出使用相同的类型,并明确选择要在您的函数中使用的类型。例如:
template < class T >
T smaller ( T a, T b ){
return (a<b?a:b);
}
int main {
int x = 98;
double y = 15.45;
// cout << smaller( x , y ) << endl; //This wouldn't compile. It would compile if x and y had the same type.
// cout << smaller<int>( x , y ) << endl; //This would still return 15
cout << smaller<double>( x , y ) << endl;
}
正如 user2079303 提到的,您尝试实现的函数与标准库中可用的 std::min 函数非常相似。
关于c++ - 整数到 double 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25723287/