cast cpp
#include <iostream>
using namespace std;
int main() {
float f = 10.5;
int i;
i = static_cast<int>(f);
cout << "Float f: " << f << endl;
cout << "Int i after casting: " << i << endl;
return 0;
}
Explanation:
#include <iostream>
: Includes the input/output stream library to perform input and output operations.using namespace std;
: Allows the usage of elements in thestd
namespace without prefixing them withstd::
.int main() { ... }
: The main function where the program execution begins.float f = 10.5;
: Declares and initializes a float variablef
with the value 10.5.int i;
: Declares an integer variablei
.i = static_cast<int>(f);
: Usesstatic_cast
to explicitly convertf
from a float to an integer, assigning the result toi
.cout << "Float f: " << f << endl;
: Outputs the value of variablef
.cout << "Int i after casting: " << i << endl;
: Outputs the value of variablei
after the casting operation.return 0;
: Indicates successful program execution and terminates themain
function.