Temperature Converter
Unit conversion practices floating-point arithmetic and formatted output.
What is Temperature Converter?
Unit conversion practices floating-point arithmetic and formatted output.
Convert Celsius to Fahrenheit.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
C and C++ code examples
main.c
#include <stdio.h>
int main(void) {
double celsius = 25.0;
// Floating-point constants preserve fractional values.
double fahrenheit = celsius * 9.0 / 5.0 + 32.0;
printf("%.1f C = %.1f F\n", celsius, fahrenheit);
}
25.0 C = 77.0 F
C++
main.cpp
#include <iomanip>
#include <iostream>
int main() {
double celsius = 25.0;
// Floating-point constants preserve fractional values.
double fahrenheit = celsius * 9.0 / 5.0 + 32.0;
std::cout << std::fixed << std::setprecision(1) << celsius << " C = " << fahrenheit << " F\n";
}
25.0 C = 77.0 F
C and C++ comparison
Use floating-point constants so division does not truncate the fractional component.
C
C exposes small procedural APIs and makes representation details explicit.
C++
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.