整数到双精度的转换
Integer to double conversion
如何将整数转换为双精度?我有这个代码,它的结果是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++11中,可以将尾部返回类型与decltype
和std::decay
(或者std::common_type
)一起使用:
template < class T1 , class T2 >
auto smaller ( T1 a, T2 b ) -> typename std::decay<decltype(a<b?a:b)>::type {
return (a<b?a:b);
}
decay
是确保函数按值返回所必需的。由于您按值获取参数,因此无法返回引用。
在C++14中,您可以使用退货类型扣除:
template < class T1 , class T2 >
auto smaller ( T1 a, T2 b ) {
return (a<b?a:b);
}
在C++11之前,您可以编写一个非常复杂的promotion_traits
类,其中包含许多专门化,以确定适当的返回类型并返回typename promotion_traits<T1, T2>::type
,或者您可以按照Antonio的建议,在一个模板参数上模板化smaller
,在这种情况下,它变为std::min
,但通过值而不是常量引用传递。
在函数调用中,尝试将x强制转换为双精度。
(double)x //or
static_cast<double>(x)
相关文章:
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 如何从字符串转换为双精度*
- C++如何将字符串逐行转换为双精度
- 如何防止双精度值到整数的隐式转换
- 如果存在从"双精度"到"T"的转换,则禁用构造函数
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将双精度值转换为 char 变量时字符串流如何工作
- 从二进制流中读取时,将双精度变量的地址转换为 char* 意味着什么?
- 在 c++ 中从双精度转换为字符串
- 如何在C++中将无符号字符缓冲区转换为双精度?
- 从字符串转换为双精度和整数 - C++
- 如何使用按位运算将随机uint64_t转换为范围 (0, 1) 的随机双精度
- 使用 sprintf 和 %g 将双精度转换为字符串的意外结果
- 表达式中应用的转换(双精度为整数)
- 无法转换双精度 - 新运算符
- C++类型转换双精度