C++ Learning Notes 3

Data Types:C++ requires that when creating a variable or constant, the corresponding data type must be specified; otherwise, memory cannot be allocated for the variable.The significance of data types: to allocate appropriate memory space for variables.Integer Types:Function: Integer variables represent integer data types.In C++, the following types can represent integers,with differences in the memory space they occupy.C++ Learning Notes 3Example Code:

#include <iostream>
using namespace std;

int main(){
	// Integer Types
	// 1. Short Integer
	short num1 = 10;
	// 2. Integer
	int num2 = 10;
	// 3. Long Integer
	long num3 = 10;
	// 4. Long Long Integer
	long long num4 = 10;

	cout << "num1=" << num1 << endl;
	cout << "num2=" << num2 << endl;
	cout << "num3=" << num3 << endl;
	cout << "num4=" << num4 << endl;
	cout << sizeof(num1) << endl;
	cout << sizeof(num2) << endl;
	cout << sizeof(num3) << endl;
	cout << sizeof(num4) << endl;
	system("pause");
	return 0;
}

Execution Result:C++ Learning Notes 3We can use the sizeof function to check the size of data types. It can be seen that the long long type occupies 8 bytes of memory.In development, the most commonly used type is int.sizeof Keyword:Function: The sizeof keyword can be used to count the memory size occupied by a data type.Syntax: sizeof(data type/variable)See example above.Comparison of Integer Sizes: short < int < long <= long longFloating Point Types:Function: Represents decimal numbers.There are two types of floating point variables:1. Single Precision float2. Double Precision doubleThe difference between them lies in the range of significant digits they can represent.C++ Learning Notes 3Example Code:

#include <iostream>
using namespace std;

int main(){
	float f1 = 3.1415926f;
	double d1 = 3.14;
	cout << "f1=" << f1 << endl;
	cout << "d1=" <<  d1 << endl;
	system("pause");
	return 0;
}

C++ Learning Notes 3C++ Learning Notes 3By default, when outputting a decimal, it will display 6 significant digits.Counting the memory size occupied by float and double:

#include <iostream>
using namespace std;

int main(){
	float f1 = 3.1415926f;
	double d1 = 3.14;
	cout << "f1=" << f1 << endl;
	cout << "d1=" <<  d1 << endl;
	cout << sizeof(float) << endl;
	cout << sizeof(double) << endl;
	system("pause");
	return 0;
}

C++ Learning Notes 3C++ Learning Notes 3It can be seen that the float data type occupies 4 bytes, while the double data type occupies 8 bytes.Scientific Notation:

#include <iostream>
using namespace std;

int main(){
	float f1 = 3.1415926f;
	double d1 = 3.14;
	cout << "f1=" << f1 << endl;
	cout << "d1=" <<  d1 << endl;
	cout << sizeof(float) << endl;
	cout << sizeof(double) << endl;
	// Scientific Notation
	float f2 = 3e2;    // 3 * 10^2
	cout << "f2=" << f2 << endl;
	float f3 = 3e-2;   // 3 * 0.1^2
	cout << "f3=" << f3 << endl;
	system("pause");
	return 0;
}

Execution Result:C++ Learning Notes 3

Leave a Comment