c++ - 整数到 double 的转换

标签 c++ templates integer double

如何将整数转换为 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/

相关文章:

c++ - 使用堆的优先级队列,具有相同键的值不遵循FIFO(先进先出)

c++ - PWCHAR 转字符串

c++ - 对 `cvCreateBGCodeBookModel' 的 undefined reference

c++ - 检查模板参数

c++ - C++ 模板函数中根据类型名调用不同的构造函数

java - java中的 "integer"相当于javascript中的什么?

python - 如何在 Python 和 C++ 之间交换数据

c++ - 简单的子类模板模式

ruby - 如何在 ruby​​ 中声明 8 位无符号整数?

java - 输入整数时,整数不会保存在 SQL 中