How to covert int to float

Hey guys

I have a question here

How I want to convert an int to float in the middle of the program

#include <iostream>

using namespace std;

int main()
{
int x;
float y;

cin>> x;

y= (float)x;

cout<< y;
}

is this line correct y= (float)x;?

thanks guys
Yes, it is correct.

Any suitable types could be converted using such "type cast" operator which looks like type name inside parentheses.

However, int needs not to be converted to float manually since it would be done automatically on assignment.

1
2
3
4
int x;
float y;
y = x;
x = (int) y;
Last edited on
is this line correct y= (float)x;?

Yes, but that is a C style cast. In C++ programs you should favor C++ style casts, which are easier to spot.

y = static_cast<float> (x);

http://www.cplusplus.com/doc/tutorial/typecasting/
Topic archived. No new replies allowed.