0 -17
20 -6
40 4
60 15
80 26
100 37
120 48
140 60
160 71
180 82
200 93
220 104
240 115
260 126
280 137
300 148
결과 값은 이렇답니다.
source code
#include <stdio.h> main() { int fahr, celsius; int lower, upper, step; lower = 0; /* lower limit of temperature table*/ upper = 300; /* upper limit */ step = 20; /* step size */ fahr = lower; while(fahr <= upper) { celsius = 5 * ( fahr - 32 ) / 9; printf("%d \t %d\n", fahr, celsius); fahr = fahr + step; } }
\t는 출력 콘솔에서 8칸을 띄운다는 문법적인 약속이죠. 이스케이프 시퀀스라던가요?
while( fahr <= upper )
이 문장은 fahr값이 upper 보다 작거나 같을 때 까지만 true다. 즉 true인 동안 loop 문장을 수행하여라.
celsius = 5 * ( fahr - 32 ) / 9 이 값에서 실수가 나온다 하더라도 정수형 변수인 celsius는 소수점 값을 탈락 시킵니다. 하지만 이 값에선 실수값은 나오지 않습니다. ㅎㅎ
정수연산만 하고 있기 때문입니다.
*대부분 책과 비슷하게 타이핑 하려고 했으나 저만의 코딩 습관은 괄호 사이 간격과 띄워쓰기 , 들여쓰기 정도이고 중괄호는 항상 라인에 맞춰서 쓰기에 좀 다릅니다. ^^
두 번째 version
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
#include <stdio.h> main() { float fahr, celsius; int lower, upper, step; lower = 0; /* lower limit of temperature table*/ upper = 300; /* upper limit */ 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; } }
소수 점을 사용하는 실수형 float형으로 계산 한겁니다.
3.0f 혹은 6.1f가 보이시나요?
이것은 포맷인 f 와 함께 정밀도를 지정하고 , 출력될 칸 수를 지정하는 겁니다.
%3f는 최소한 3칸을 차지하여, 실수 값을 나타낸다 이런 뜻이라는군요.
%3.2f 는 최소한 3칸을 차지하여 소수점 2자리 까지만 출력하라 이런 뜻입니다.
'프로그래밍 > C언어' 카테고리의 다른 글
1.5.1 File Copying 2nd version (0) | 2011.11.07 |
---|---|
1.5.1 File Copying (0) | 2011.11.07 |
1.5 Character Input and Output (0) | 2011.11.07 |
1.4 Symbolic Constants (0) | 2011.11.07 |
1.3 The for Statement (0) | 2011.11.07 |