C++ Float Data Type Explained

In C++, float is a fundamental data type used to store single-precision floating point numbers. It is typically used to represent decimal values, with 7 significant digits, and usually occupies 4 bytes of space in memory. Float can be used to store data that requires retaining the decimal part, such as floating-point operations, scientific calculations, etc.

Here is an example using float.

#include <iostream>

int main() {
    float num1 = 3.14f;  // 定义一个float类型的变量num1,赋值为3.14
    float num2 = 2.5f;   // 定义一个float类型的变量num2,赋值为2.5
    
    float sum = num1 + num2;  // 将num1和num2相加并保存到sum变量中
    std::cout << "Sum of " << num1 << " and " << num2 << " is: " << sum << std::endl;
    
    return 0;
}

In the example above, we defined two variables of type float, num1 and num2, with values of 3.14 and 2.5 respectively. We then added them together and saved the result in the variable sum. Finally, we used cout to output the sum of these two numbers.

bannerAds