float to int c++

To convert a float to an int in C++, you can use the static_cast or int constructor. Here are the steps to perform this conversion:

  1. Declare a float variable: Begin by declaring a variable of type float and assign it a value.
float myFloat = 3.14;
  1. Convert float to int: To convert the float to an int, use either the static_cast operator or the int constructor. Both methods will truncate the decimal portion of the float value.

Using static_cast:

int myInt = static_cast<int>(myFloat);

Using int constructor:

int myInt = int(myFloat);
  1. Use the int value: The resulting int value can now be used in your code. Keep in mind that the decimal portion of the float will be discarded, and the int variable will only hold the whole number part.
std::cout << "Converted value: " << myInt << std::endl;

This will output:

Converted value: 3

By following these steps, you can convert a float to an int in C++.