Simple programs using Operators, and type conversion.
Aim
The aim is to illustrate the mechanism of explicit type conversion using the Type Cast Operator in C++. This exercise demonstrates how values are handled when converting between basic integer (int) and floating-point (float) data types, specifically employing the C++ function-call notation for casting.
Algorithm
Initialize an integer variable (
intvar) with the value 25.Initialize a floating-point variable (
floatvar) with the value 35.87.Display the initial values of
intvarandfloatvar.Apply explicit type casting using
float(intvar)to convert the integer value to a float, and display the result.Apply explicit type casting using
int(floatvar)to convert the float value to an integer, and display the result.Terminate the program.
Program
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int intvar=25;
float floatvar=35.87;
cout<<"intvar = "<<intvar;
cout<<"\nfloatvar = "<<floatvar;
cout<<"\nfloat(intvar) = "<<float(intvar);
cout<<"\nint(floatvar) = "<<int(floatvar);
getch();
}
Output
intvar = 25
floatvar = 35.87
float(intvar) = 25
int(floatvar) = 35
Result/Discussion
The program successfully demonstrates the use of the explicit type cast operator in C++ notation, specifically type-name (expression). When the integer variable intvar (value 25) was converted to a float, the result retained the value 25. However, when the float value 35.87 was explicitly converted to an integer using int(floatvar), the fractional part of the value was truncated, yielding the result 35. C++ permits this explicit conversion, allowing the programmer control over type handling, even when it results in a loss of precision.