CHAPTER 35. TEMPERATURE CONVERTING CHAPTER 35. TEMPERATURE CONVERTING
Chapter 35
Temperature converting
Another very popular example in programming books for beginners is a small program that converts Fahrenheit temperature
to Celsius or back.
C=
5 ⋅(F−32)
9
We can also add simple error handling: 1) we must check if the user has entered a correct number; 2) we must check if the
Celsius temperature is not below− 273 (which is below absolute zero, as we may remember from school physics lessons).
Theexit()function terminates the program instantly, without returning to thecallerfunction.
35.1 Integer values
#include <stdio.h>
#include <stdlib.h>
int main()
{
int celsius, fahr;
printf ("Enter temperature in Fahrenheit:\n");
if (scanf ("%d", &fahr)!=1)
{
printf ("Error while parsing your input\n");
exit(0);
};
celsius = 5 * (fahr-32) / 9;
if (celsius<-273)
{
printf ("Error: incorrect temperature!\n");
exit(0);
};
printf ("Celsius: %d\n", celsius);
};
35.1.1 Optimizing MSVC 2012 x86.
Listing 35.1: Optimizing MSVC 2012 x86
$SG4228 DB 'Enter temperature in Fahrenheit:', 0aH, 00H
$SG4230 DB '%d', 00H
$SG4231 DB 'Error while parsing your input', 0aH, 00H
$SG4233 DB 'Error: incorrect temperature!', 0aH, 00H
$SG4234 DB 'Celsius: %d', 0aH, 00H
_fahr$ = -4 ; size = 4
_main PROC