'Int'不能转换为'double'类型

时间:2013-12-03 05:46:11

标签: c++ int double visual-c++

我在运行时不断收到此错误:“'Int'不能转换为'double'类型”,它会在我运行程序时立即显示,但随后它会很快消失然后显示我的程序。我正在使用VC2010。 (编辑:这个程序是将摄氏温度转换为华氏温度,并判断它是热还是不热。)

#include <iostream>

int convert(int);

int main(void)
{
     using std::cout;
     using std::cin;
     using std::endl;

     cout << "Enter the degrees in Celsius: ";

     int temp;
     cin >> temp;
     int degrees = convert(temp);

if(degrees<100)
{
    cout << degrees << " is not too hot." << endl;
}

else if(degrees>100)
{
    cout << degrees << " is hot." << endl;
}

      cin.get();
      cin.get();
      return 0;
    }


int convert(int ctf)
{
     return ctf * 1.8 + 32;
}

3 个答案:

答案 0 :(得分:2)

您应该将convert方法的结果显式地转换为int以避免此消息。

int convert(int ctf)
{
     return (int) (ctf * 1.8 + 32);
}

由于返回类型指定为广告int,但浮点乘法的结果不是int,因此显示此消息。
但是,由于您要将温度从摄氏温度转换为华氏温度,因此最好使用doublefloat值而不是int来产生更准确和有意义的输出。

答案 1 :(得分:1)

通过指定convert返回int而表达式ctf * 1.8 + 32返回double作为{{1},您收到编辑器警告,告知您精度下降类型为1.8。涉及doubleint类型变量的算术表达式会将结果类型提升为double。我建议您将double功能更新为:

convert

如果你坚持使用整数,请进行适当的演员:

double convert(double ctf)

答案 2 :(得分:0)

我认为您的错误在转换函数中,通过将int与小数相乘,您将自动将其转换为double。所以要么返回一个double,要么将其强制转换为int

相关问题