Jake2k13
Jake2k13

Reputation: 231

'Int' is not convertible to type 'double'

I keep getting this error at run-time: "'Int' is not convertible to type 'double'", it displays this as soon as I run the program, but then it quickly disappears and then shows my program. I'm using VC2010. (EDIT: This program is to convert Celsius to Fahrenheit, and to tell if it's hot or not hot.)

#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;
}

Upvotes: 2

Views: 942

Answers (3)

user425495
user425495

Reputation:

You are getting a compiler warning informing you of a loss of precision by specifying that convert returns an int while the expression ctf * 1.8 + 32 returns a double as 1.8 is of type double. Arithmetic expressions involving variables of type int and double will promote the resulting type to double. I recommend updating your convert function to:

double convert(double ctf)

If you insist on using integers, make the appropriate cast:

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

Upvotes: 1

Infinite Recursion
Infinite Recursion

Reputation: 6557

You should explicitly cast the result of convert method to int to avoid this message.

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

Since the return type is specified ad int, but the result of the float multiplication is not int, it is showing this message.
However, since you are converting temperatures from Celsius to Fahrenheit, it is better to use double or float values instead of int to yield more accurate and meaningful output.

Upvotes: 2

Pita
Pita

Reputation: 1474

I think your error is in the convert function, by multiplying a int with a decimal you are automatically converting it to a double. so either return a double, or cast it to a int

Upvotes: 0

Related Questions