Float - Double
Part of the Fundamentals section of Coddy's C journey — lesson 7 of 63.
Float and double are data types used to store decimal numbers in C.
Declare a float variable:
float price = 19.99f;Notice the 'f' suffix, which tells C this is a float value.
Declare a double variable:
double pi = 3.14159265359;The main differences between float and double:
- Precision: Double has higher precision than float
- Float: ~7 decimal digits
- Double: ~15 decimal digits
- Size:
- Float: 4 bytes
- Double: 8 bytes
- Range:
- Float: 1.2E-38 to 3.4E+38
- Double: 2.3E-308 to 1.7E+308
Print a float value:
float temperature = 98.6f;
printf("Temperature is %f degrees\n", temperature);Print with specific decimal places:
printf("Temperature is %.1f degrees\n", temperature);This will show: “Temperature is 98.6 degrees”
Challenge
EasyWrite a program that:
- Declares a float variable named
celsius - Declares a double variable named
fahrenheit - Assigns the value 25.0 to
celsius - Converts celsius to fahrenheit using the formula:
fahrenheit = (celsius * 9.0/5.0) + 32.0 - Prints the result as
25.0 degrees Celsius is equal to 77.0 degrees Fahrenheit
Make sure to display precisely one decimal place in your output. The spelling of Celsius and Fahrenheit must match exactly.
To print both variables in a single printf, use %.1f as a placeholder for each number. Replace celsius and fahrenheit with your actual variable names:
printf("%.1f degrees Celsius is equal to %.1f degrees Fahrenheit\n", celsius, fahrenheit);Here, the first %.1f will be replaced by the value of celsius, and the second %.1f will be replaced by the value of fahrenheit. The \n at the end moves the cursor to a new line.
Cheat sheet
Float and double are data types for decimal numbers in C.
Declare a float variable (note the 'f' suffix):
float price = 19.99f;Declare a double variable:
double pi = 3.14159265359;Key differences:
- Precision: Float (~7 digits), Double (~15 digits)
- Size: Float (4 bytes), Double (8 bytes)
- Range: Float (1.2E-38 to 3.4E+38), Double (2.3E-308 to 1.7E+308)
Print float values:
printf("Temperature is %f degrees\n", temperature);Print with specific decimal places:
printf("Temperature is %.1f degrees\n", temperature);Try it yourself
#include <stdio.h>
int main() {
// Write your code here
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge