
In the last lesson, we discussed the float data type, which seems like a simple variable type but actually hides many “mysteries”. Its declaration methods are diverse, and the output results are often unexpected. Today, we will delve into how to use float correctly and unveil the mysterious veil of “precision loss” that may occur in calculations!
01
Declaration and Initialization of Float Variables: The Secret of F
The declaration methods for the float type are indeed flexible and varied, but when using it, we need to develop a few habits, especially in enterprise-level development, which is crucial!
First, let’s look at the most basic declaration and initialization:
#include <stdio.h>
int main() {
// Declare and initialize a float variable
float temperature = 36.5F; // Note the 'F' here!
// You can also declare first and assign later
float humidity;
humidity = 48.3F;
// ... other code ...
return 0;
}
[Professional Correction and Supplement: The Mandatory Suffix of F]]
Previously, we mentioned that an F needs to be added after 36.5, which is very correct. In C language, a floating-point constant like 36.5 is, by default, of type double (double precision floating-point number). If you want to explicitly specify it as a float type, you must add an F or f suffix after it, such as 36.5F or 36.5f. The benefits of doing this are:
-
Avoid Implicit Type Conversion: If you do not add F, 36.5 will be treated as a double, and when assigned to a float variable, implicit type conversion will occur, which may lead to unnecessary overhead and even potential precision issues (although not obvious in this simple example).
-
Clarify Code Intent: Clearly indicate that you expect this to be a single-precision floating-point number.
This is similar to adding U (unsigned) or L (long) after integer constants.
02
Variable Naming Conventions: Say Goodbye to A, B, C!
In enterprise-level project development, variable naming is no joke! We strongly criticize the practice of using meaningless variable names like A, B, C, D, which is absolutely not allowed in actual projects.
Incorrect Example::
float a = 1.2F;
float b = 3.4F;
float c = 5.6F;
This kind of code, apart from the author, no one can know what a, b, and c actually represent.
Correct Approach::
float temperature = 36.5F; // Temperature
float humidity = 48.3F; // Humidity
float speedOfSound = 343.2F; // Speed of sound
Variable names should be descriptive and clearly express the meaning of the data they store.
[Deepening Understanding: The Importance of Variable Naming]
-
Readability and Maintainability: Good variable naming can greatly enhance the readability of the code. When team members or your future self review the code, they can immediately understand the purpose of the variables, thus reducing the cost of understanding and maintenance.
-
Mapping with Database Fields: As emphasized earlier, in backend development, many variables will map to database fields. If variable names are meaningless, then database design and data interaction will become chaotic.
-
The Concept of Schema: A combination of multiple meaningful variables forms a clear data schema, which is crucial for building robust software systems.
03
Multiple Definitions and Scientific Notation: Flexibly Using Float
In addition to regular declarations, float also supports some more advanced usages.
Scientific Notation:
When dealing with very large or very small floating-point numbers, scientific notation is a convenient way to express them.
float distance = 3.45E2F; // 3.45 x 10^2 = 345.0
// Here, 'E2' means 'multiplied by 10 to the power of 2'
[Review of Mathematical Basics]
If you are not familiar with E representing scientific notation, simply put, xEny means x * 10^y. So 3.45E2F is 3.45 * 10^2, which equals 345.0.
Multiple Definitions:
When you have multiple variables of the same type to declare, you can use commas for multiple definitions.
// This multiple definition applies to logically related variables
float length = 23.45F, width = 12.34F, height = 5.67F; // Assuming they form a cube
[Note! Applicable Scenarios for Multiple Definitions]
It is particularly emphasized that while multiple definitions are syntactically allowed, they need to be used cautiously in practice. It is not recommended to mix unrelated variables (such as temperature, humidity, speed) in the same definition.
Not Recommended::
float temperature = 36.5F, humidity = 48.3F, speed = 100.0F; // Logically not part of a whole
Recommended::
Only when these variables logically form a tight “whole” (for example, the length, width, and height of an object, or the x, y, z coordinates of a coordinate system) should multiple definitions be used. Otherwise, for the sake of code clarity and readability, it is best to declare them separately.
04
Output of Float: %f and the Prelude to Precision Loss
To output float type data, we use the printf function with the %f format specifier.
#include <stdio.h>
int main() {
float temperature = 36.5F;
float humidity = 48.3F;
float distance = 3.45E2F; // 345.0F
float ratio = 34.56F;
printf("Temperature: %.2f\n", temperature); // Limit output to two decimal places
printf("Humidity: %f\n", humidity);
printf("Distance: %f\n", distance);
printf("Ratio: %f\n", ratio);
return 0;
}
[Code Example Output]
Temperature: 36.50
Humidity: 48.299999
Distance: 345.000000
Ratio: 34.559999
Hey, did you notice some strange phenomena in the output results? Why did the values of humidity and ratio become 48.299999 and 34.559999 instead of the expected 48.3 and 34.56? Yet temperature and distance displayed normally?
This is the “precision loss” issue mentioned earlier, which is one of the most troublesome characteristics of the float type!
05
Naming Style: Camel Case or Underscore?
Two common variable naming styles are mentioned:
-
Camel Case: (Camel Case):
-
Lower Camel Case: (lowerCamelCase): The first letter is lowercase, and the first letter of each subsequent word is uppercase. For example: temperature, speedOfSound.
-
Upper Camel Case: (UpperCamelCase / Pascal Case): The first letter of each word is uppercase. Mainly used for class names or struct names.
-
Commonly found in: Object-oriented programming languages like Java, C#.
-
Underscore Naming Style: (Snake Case):
-
Words are connected by underscores _ . For example: temperature_value, speed_of_sound.
-
Commonly found in: C language, Python, SQL.
[Normative Suggestions]
Both naming styles are correct, the key is: Maintain consistency within a project! If the team agrees to use camel case, everyone should follow; if it is agreed to use underscore naming, then stick to underscores. Confusing naming styles will reduce the integrity and professionalism of the code. In classic C language code, underscore naming is more common.
06
Summary
Today we learned about the definition, initialization, naming conventions, and output of the float type. The core points are summarized as follows:
-
Precision First: Add F after float constants to clarify the type and avoid implicit conversion.
-
Naming Conventions: Variable names must be meaningful, say goodbye to A, B, C, ensuring code readability and maintainability.
-
Beware of Precision: The float type has precision loss issues that need special attention!
