Type casting program in c++

Data type casting in c++ program
#Beginner

In gcc c++ compiler using namespace std;



#include <iostream>
using namespace std;

int main()
{
cout << "float to int " << (int)1.35 << endl;
cout << "int to float " << (float)36 << endl;
cout << "char to int " << (int)'A' << endl;

cout << endl;

int int_num1 = 35;
float float_num1 = 30.9;
char char_letter = 'B';

int int_num2 = (int)float_num1;
float float_num2 = (float)int_num1;

int int_char = (int)char_letter;

cout << "float to int " << int_num2 << endl;
cout << "int to float" << float_num2 << endl;
cout << "char to int " << int_char << endl;
}
copy


Output 

float to int 1
int to float 36
char to int 65

float to int 30
int to float35
char to int 66

[Program finished]


OR


In gcc c++ compiler using namespace std;



#include <iostream>
using namespace std;

int main()
{
cout << "float to int " << static_cast<int>(1.35)<< endl;
cout << "int to float " << static_cast<float>(36)<< endl;
cout << "char to int " << static_cast<int>('A') << endl;

cout << endl;

int int_num1 = 35;
float float_num1 = 30.9;
char char_letter = 'B';

int int_num2 = static_cast<int>(float_num1);
float float_num2 = static_cast<int>(int_num1);
int int_char = static_cast<int>(char_letter);

cout << "float to int " << int_num2 << endl;
cout << "int to float " << float_num2 << endl;
cout << "char to int " << int_char << endl;
}


Output

float to int 1
int to float 36
char to int 65

float to int 30
int to float 35
char to int 66

[Program finished]


Need of Programmer

Need of Programmer

Comments

Popular posts from this blog

Write a program that reads in the radius and length of a cylinder and computes the area and volume using the following formulas: area = radius * radius * π volume = area * length

Write a program that reads the subtotal and the gratuity rate, then computes the gratuity and total. For example, if the user enters 10 for subtotal and 15% for gratuity rate, the program displays $1.5 as gratuity and $11.5 as total.

Write a program that prompts the user to enter the min- utes (e.g., 1 billion), and displays the number of years and days for the minutes. For simplicity, assume a year has 365 days