整数到双精度的转换

Integer to double conversion

本文关键字:转换 双精度 整数      更新时间:2023-10-16

如何将整数转换为双精度?我有这个代码,它的结果是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中,可以将尾部返回类型与decltypestd::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)