# C intro 3. Variables

Up to this point, we have tried simple calculations mainly by handling integers, but in actual practice and research, it will be necessary to handle real numbers (not just integers but also numbers like -1.23 or 3.1415). To calculate real numbers, use a variable of the type called "floating point number".

Floating point number treats a real number as two parts: significant values and exponents. It enables treatment of a huge range of real values.

Specifically, there are two types of real types: float type and double type. The difference is how much information amount to handle one real number. The float type handles one real number with 4 bytes of information amount, but the double type handles one real number with 8 bytes. Naturally, the latter can handle real numbers in a larger range and more accurately. The differences are summarized as follows:

• float type (single float type) ... (4 bytes, about 1.5 × 10-45 〜 3.4 × 1038)
• double type (double float type) ... (8 bytes, about 5.0 × 10-324 〜 1.7 × 10308)

Use of the double type is advantageous for avoiding errors and getting accurate results in calculations, but on the other hand, it uses more memories and the processing speed is slower.

Here is an example of a program which handles real numbers. It calculates 1/1 + 1/2 + 1/3 + ... + 1/9. (Do not input the numbers on the head of each line)：

```    1. /* float_test.c */
2. /* 2008/07/15 K. Nasahara */
3. /* 1/1 + 1/2 + 1/3 + ... + 1/9 */
4. # include <stdio.h>
5. main()
6. {
7. int i;
8. float s=0;
9. for (i=1; i<=9; i++)
10.   s=s+1.0/i;        // Write it not 1 but 1.0 for make it clear that it is a real number.
11. printf("%f\n", s);  // Format of a real number in printf is %f.
12. }
```

The line 10 is the computation part, but here it does not work if 1/i is used instead of 1.0/i. That is because i is an integer type variable, 1/i is a division of integers, and the operation is performed within the range of integers. That is, if i is 2 or more, 1/i is calculated as zero (because it is less than 1). To avoid this, express 1 as 1.0, then the computer recognize that it is necessary to calculate in real number.

Exercise　Make a program which reads a single integer n from the keyboard and calculate the sum of reciprocals of squares of numbers from 1 to n. If n is sufficiently large, this sum should be 1.64493 ... (pi * pi / 6).

[Go back to C language introduction]