4
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 5 years have passed since last update.

defineで定めた定数値の計算

Last updated at Posted at 2015-10-12

defineで値を定め、その値を計算するときに思い通りにならないことがあったのでメモ。
こんな初歩的内容でも超初心者に役立てば幸い!

経緯

define constant01 30
define constant02 20
などとして定数を定めて
double d_var = constant01/constant02;
等と書いて計算させたがなぜか切り捨てられて1.0になってしまう。

結論

define constant01 20 //小数を付けなければint(整数)として扱われる
define constant02 20.0 //小数を付ければdoubleとして(?)扱われる

確認src

main_study01.c
# include <stdio.h>
# include <stdlib.h>
# include <math.h>

# define input_def01 15
# define input_def02 6

int main(int argc,char *argv[]) {
        printf("this is define input study\n");
        int int_devided=0;

        //割り算をしてint型変数へ格納する 答えは2.5で切り捨てで2がint_devidedへ格納される
        int_devided = input_def01/input_def02;
        printf("devide of define_input is %d\n",int_devided);

        //割り算をしてdouble型変数へ格納する 答えの2.5がdouble_devidedへ格納されるハズだが...
        double double_devided =  input_def01/input_def02;
        printf("devide of define_input is %f\n",double_devided);//2.0が出力された!

        //いったんdouble型変数に格納してから計算すると
        double def01 = input_def01;
        double def02 = input_def02;
        double_devided =  def01/def02;
        printf("devide of double from define_input is %f\n",double_devided);//2.5が出力された
}
$ gcc main_study01.c -o study.exe

$ ./study.exe
this is define input study
devide of define_input is 2
devide of define_input is 2.000000
devide of double from define_input is 2.500000

以上。

4
2
1

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
4
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?