C++において、
小数点以下の扱いについて質問です。
a=1.234
b=2.345
として、
このaとbを少数以下の数字で判別する事は可能でしょうか???
気になる質問をクリップする
クリップした質問は、後からいつでもMYページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
回答2件
0
ベストアンサー
lang
1#include <stdio.h> 2#include <math.h> // for floor(), fabs() 3#include <float.h> // for DBL_MIN 4 5const double DELTA = DBL_MIN; 6 7int compare_decimals(double a, double b, double delta) { 8 double a0 = a - floor(a); 9 double b0 = b - floor(b); 10 if (fabs(a0 - b0) < delta) { 11 return 0; 12 } else if (a < b) { 13 return 1; 14 } else { 15 return -1; 16 } 17} 18 19int main(int argc, char** argv) { 20 21 double a; 22 double b; 23 24 a = 1.234; 25 b = 2.234; 26 printf("%d %f, %f\n", compare_decimals(a, b, 0.0), a, b); 27 printf("%d %f, %f\n", compare_decimals(a, b, DELTA), a, b); 28 printf("%d %f, %f\n", compare_decimals(a, b, 0.00001), a, b); 29 printf("\n"); 30 31 a = 1.234; 32 b = 1e1 + 0.234; 33 printf("%d %f, %f\n", compare_decimals(a, b, 0.0), a, b); 34 printf("%d %f, %f\n", compare_decimals(a, b, DELTA), a, b); 35 printf("%d %f, %f\n", compare_decimals(a, b, 0.00001), a, b); 36 printf("\n"); 37 38 a = 1.234; 39 b = 1e10 + 0.234; 40 printf("%d %f, %f\n", compare_decimals(a, b, 0.0), a, b); 41 printf("%d %f, %f\n", compare_decimals(a, b, DELTA), a, b); 42 printf("%d %f, %f\n", compare_decimals(a, b, 0.00001), a, b); 43 printf("\n"); 44 45 a = 1.0 + 1.0/3; 46 b = 2.0 + 1.0/3; 47 printf("%d %f, %f\n", compare_decimals(a, b, 0.0), a, b); 48 printf("%d %f, %f\n", compare_decimals(a, b, DELTA), a, b); 49 printf("%d %f, %f\n", compare_decimals(a, b, 0.00001), a, b); 50 printf("\n"); 51 52 return 0; 53}
実行例
1 1.234000, 2.234000 0 1.234000, 2.234000 0 1.234000, 2.234000 1 1.234000, 10.234000 0 1.234000, 10.234000 0 1.234000, 10.234000 1 1.234000, 10000000000.233999 1 1.234000, 10000000000.233999 0 1.234000, 10000000000.233999 1 1.333333, 2.333333 1 1.333333, 2.333333 0 1.333333, 2.333333
小数点以下の部分をとりだすのは floor() 関数で行えます。
ただし、double や float の値を比較する際は注意が必要です。
上のプログラムの例では
(1.234, 2.234) の比較と (1.234, 1e10 + 0.234) の比較は、 比較の許容値によって比較結果が変わってしまいます。
目的・状況に合わせて許容値を設定することが必要です。
投稿2015/03/07 22:22
総合スコア22324
0
少数以下の数字で判別するというのは少数点以上の数字を0にし比較するという意味でいいでしょうか?それであれば <cmath> ヘッダをインクルードし (a - floor(a)) > (b - floor(b)) などとすれば出来ます。a や b がプラスの値であればですが。
投稿2015/03/07 20:21
編集2015/03/07 20:39総合スコア24
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
あなたの回答
tips
太字
斜体
打ち消し線
見出し
引用テキストの挿入
コードの挿入
リンクの挿入
リストの挿入
番号リストの挿入
表の挿入
水平線の挿入
プレビュー
質問の解決につながる回答をしましょう。 サンプルコードなど、より具体的な説明があると質問者の理解の助けになります。 また、読む側のことを考えた、分かりやすい文章を心がけましょう。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/03/08 05:03