2013年12月14日土曜日

開発環境

C実践プログラミング 第3版 (Steve Oualline (著)、 望月 康司 (監訳) (翻訳)、谷口 功 (翻訳)、オライリー・ジャパン)のⅡ部(単純なプログラミング)の16章(浮動小数点数)、16.12(プログラミング実習)、実習 16-2を解いてみる。

その他参考書籍

実習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 コメント:

コメントを投稿