Assigning Values to Float Variables
Once you have declared a float variable, you can assign a value to it using the assignment operator (=
). Here are some examples:
float pi = 3.14159f;
float radius = 5.0f;
float area = pi * radius * radius;
In the above example, we assign the value 3.14159
to the pi
variable, 5.0
to the radius
variable, and then calculate the area
variable by multiplying pi
and radius
.
You can also assign the value of one float variable to another:
float x = 2.5f;
float y = x;
In this case, the value of x
(2.5) is assigned to the y
variable.
Additionally, you can perform arithmetic operations on float variables and assign the result to another float variable:
float num1 = 10.0f;
float num2 = 3.5f;
float sum = num1 + num2;
float difference = num1 - num2;
float product = num1 * num2;
float quotient = num1 / num2;
In the above example, we perform addition, subtraction, multiplication, and division on the num1
and num2
variables, and assign the results to the sum
, difference
, product
, and quotient
variables, respectively.
It's important to note that when assigning values to float variables, you should use the f
or F
suffix to indicate that the value is a float, as opposed to a double, which is another floating-point data type in Java.