開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- C (プログラミング言語)
- Clang (コンパイラ)
C実践プログラミング 第3版 (Steve Oualline (著)、 望月 康司 (監訳) (翻訳)、谷口 功 (翻訳)、オライリー・ジャパン)のⅡ部(単純なプログラミング)の16章(浮動小数点数)、16.12(プログラミング実習)、実習 16-2を解いてみる。
その他参考書籍
- プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
実習16-2.
コード
sample.c
#include <stdio.h>
#include <math.h>
int main()
{
double nums[] = {1.2345, 1.2354, 12.3446, 12.3456,
-1.2345, -1.2354, -12.3446, -12.3456};
int n = 2;
int i;
double to_fixed_double(double a, int n);
for(i = 0; i < 8; i++){
printf("浮動小数点数: %f\n", nums[i]);
printf("小数点の右の桁数%dの固定小数点数: %.2f\n",
n, to_fixed_double(nums[i], n));
}
return (0);
}
double to_fixed_double(double a, int n)
{
int l, m;
double b, c;
a *= pow(10, n + 1);
l = (int) a;
m = l % 10;
if(a >= 0){
l = m >= 5 ? l + 10 : l - m;
} else {
l = m >= 5 ? l - 10 : l + m;
}
l /= 10;
return l / pow(10, n);
}
makefile
CC=cc CFLAGS=-g sample: sample.c $(CC) $(CFLAGS) -o sample sample.c clean: rm -f sample
入出力結果(Terminal)
$ make cc -g -o sample sample.c $ ./sample 浮動小数点数: 1.234500 小数点の右の桁数2の固定小数点数: 1.23 浮動小数点数: 1.235400 小数点の右の桁数2の固定小数点数: 1.24 浮動小数点数: 12.344600 小数点の右の桁数2の固定小数点数: 12.34 浮動小数点数: 12.345600 小数点の右の桁数2の固定小数点数: 12.35 浮動小数点数: -1.234500 小数点の右の桁数2の固定小数点数: -1.23 浮動小数点数: -1.235400 小数点の右の桁数2の固定小数点数: -1.24 浮動小数点数: -12.344600 小数点の右の桁数2の固定小数点数: -12.34 浮動小数点数: -12.345600 小数点の右の桁数2の固定小数点数: -12.35 $
0 コメント:
コメントを投稿