1.2 Variables and Arithmetic Expressions

The Fahrenheit to Celsius temperature convert is an epitome for beginner to know about variables and arithmetic expression
——————————————————-
/*Fahrenheit-Celsius convert #1 edition*/

# include <stdio.h>

main()
{
    int f,s;
    int low,high,step;
    low = 0;
    high = 200;
    step = 20;
    f = low;
    while(f <= high)
    {
        s = (5*(f -32))/9;
        f += step;
        printf("%d\t%d\n",f,s);
    }
    system("pause");
}
——————————————————-
for the system is lack of a pause command,I add a note in the end saying system("pause"); to pause the program when run,or it will be enclosed in a second.

 

Celsius temperature is not always in decimal but a floating number carrying with a dot and fractional part,thus this program need some modification to have a better display.
——————————————————-
/*Fahrenheit-Celsius convert #2 edition*/

# include <stdio.h>

main()
{
    int f;
    float s;
    int low,high,step;
    low = 0;
    high = 200;
    step = 20;
    f = low;
    while(f <= high)
    {
        s = (5.0/9.0)*(f -32);
        f += step;
        printf("%3d\t%6.2f\n",f,s);
    }
    system("pause");
}
——————————————————-
Bold part above consists of two float value 5.0 and 9.0,if modified as 5/9.0 or 5.0/9,it also run all the same,that because in an arithmetic expression,lower character type could be converted into higher one automatically,float is higher than int,both expression are converted into float one as 5.0/9.0.
But if modified as 5/9,it will crash.Because in this expression,both value are performed in int,and their arithmetic result should also be in an int.But 5/9 = 0.xxxxx is less than 1,and its fractional part is discarded,leaving 0 behind.

Leave a comment