1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C言語で小数点以下のみを取得する方法

Last updated at Posted at 2020-06-03

たまにド忘れするので備忘録。

方法1

小数から整数部分のみを引く。

float型をint型へキャスト変換


#include <stdio.h>

int main(void){
    float num;
    float a;

    num = 1.5;
    // int型のキャスト変換で整数化
    a = num - (int)num;
    printf("%f",a);
}

実行結果

0.500000

floor関数を用いる


#include <stdio.h>

int main(void){
    float num;
    float a;

    num = 1.5;
    
    // floor関数の性質上、負の場合は分ける
    if(num >= 0){
        a = num - floor(num);
    } else {
        a = -num - floor(-num);
    }
    printf("%f",a);
}

実行結果

0.500000

floor関数を用いる(fabs関数利用)


#include <stdio.h>

int main(void){
    float num;
    float a;

    num = 1.5;
    
    // 浮動小数点の絶対値fabs関数を利用
    a = fabs(num) - floor(fabs(num));
    printf("%f",a);
}

実行結果

0.500000

方法2

math.hのmodff関数を使う。

float modff(float value, float *iptr);

modff関数は、valueを整数部と小数部に分ける。整数部及び小数部の符号は、xと同じとなる。iptrが指すオブジェクトに整数部を格納する。


#include <stdio.h>
#include <math.h>

int main(void){
    float num;
    float a, b;

    num = 1.5;
    // aにnumの小数部、bにnum整数部が代入される
    a = modff(num,&b); 
    
    printf("%f %f",a,b);
}

実行結果

0.500000 1.000000

参考

https://masutaka.net/chalow/2004-12-10-1.html
http://www.c-lang.org/detail/function/modff.html

1
2
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?