标签:c c语言中浮点数和整数的除法 printf的宽度和精度 width and precision
Another
program to print Fahrenheit-Celsius table with decimal integer
This program is presented as below.
#include <stdio.h> /* print Fahrenheit_Celsius table for fahr = 0, 20, ..., 300; floating-point version */ int main() { float fahr, celsius; int lower, upper, step; lower = 0; /* lower limit of temperature table */ upper = 300; /* upper limit of temperature table */ step = 20; /* step size */ fahr = lower; while (fahr <= upper) { celsius = (5.0/9.0) * (fahr-32.0); printf("%3.0f %6.1f\n", fahr, celsius); fahr = fahr + step; } return 0; }
The figure of this program is presented as above. The right part of the figure is the output. This is much like the program which is mentioned at the beginning of the article, except that fahr
and celsius
are
declared to be float. We were unable to use 5/9 in the previous version because integer division would truncate it to zero. A
decimal point in a constant indicates that it is floating point, however, so 5.0/9.0 is not truncated because it is the ratio of two floating-point values.
If an arithmetic operator has integer operands, an integer operation is performed. If an arithmetic operator has one floating-point operand and one integer operand, however, the integer will be converted to floating point before the operation is done. Writing floating-point constants with explicit decimal points even when they have integral values emphasizes their floating-point nature for human readers.
For now, notice that the assignment
fahr = lower;
while (fahr <= upper)
also work in the nature way — the int is converted to float before the operation is done.
The implications of width and precision are tabled as follows.
Among others, printf
also recognizes %o
for
octal, %x
for hexadecimal, %c
for
character, %s
for charater string, and %%
for %
itself.
A program to print Fahrenheit-Celsius table with floating-point values
标签:c c语言中浮点数和整数的除法 printf的宽度和精度 width and precision
原文地址:http://blog.csdn.net/abnerwang2014/article/details/44309579