Last Updated on 2021-04-29 by Clay
The most important function of computer invented is to assist humans in computing. So, in this section, we use the conversion between Celsius (°C) and Fahrenheit (°F) to explain which is variable and which is an arithmetic expression.
If fact, this is not a complicated concept. The so-called "variable" is a name that allows us to store a specific value.
For example:
int x = 10;
That means the variable x is assigned the value 10. We can use printf()
to print the value of x any time.
The arithmetic expression is the calculation of:
- + : addition
- - : subtraction
- * : multiplication
- / : division
Conversion of Celsius (°C) and Fahrenheit (°F)
The conversion formula of Celsius (°C) and Fahrenheit (°F) is as follows:
And if it is expressed in a program, it can be written as:
#include <stdio.h> int main() { float F, C; int lower = 0; int upper = 300; int step = 20; // While F = lower; while (F <= upper) { C = (5.0 / 9.0) * (F - 32.0); printf("%3.0f %6.1f\n", F, C); F = F + step; } return 0; }
Output:
0 -17.8
20 -6.7
40 4.4
60 15.6
80 26.7
100 37.8
120 48.9
140 60.0
160 71.1
180 82.2
200 93.3
220 104.4
240 115.6
260 126.7
280 137.8
300 148.9
Here is a brief description of the meaning of each variable:
Name | Meaning |
---|---|
F | Fahrenheit |
C | Celsius |
lower | Minimum temperature boundary |
upper | Maximum temperature boundary |
step | How much temperature increase each time |
Then we use the while-loop to make F continue to execute before it is less than or equal to upper (The Maximum temperature boundary); in addition to using the formula to convert to C, don't forget to add F to the bottom of the block every time it is executed up 20 degrees.
If the temperature is not allowed to increase, the while-loop will be executed endlessly, which is probably not the result we want to see.
(Optional) printf() print variable specification
When using printf()
to print variables, we can determine the specifications of the variables to be printed. For example: %6f means at least 6 characters width, %.2f means at least two decimal points but the width is not limited. Of course, %f is to print a floating point.
symbol | description |
---|---|
%d | Print decimal integer |
%6d | Print a decimal integer, at least 6 characters width |
%f | Print floating point number |
%6f | Print floating point numbers, at least 6 characters width |
%.2f | Print floating point numbers with two decimal places |
%6.2f | Print floating point numbers, at least 6 characters width and two decimal places |
References
- http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/learninglabs/9780134309361/ch03.html
- https://www.tutorialspoint.com/format-specifiers-in-c