ストラウストラップのプログラミング入門(7) 第4章ドリル(続)
『ストラウストラップのプログラミング入門』を読む。第4章のドリル。前回はまってたドリルの続き。
4章 ドリル5(解決)
自分と同じ内容で困っている初心者の人を見つけた。
However the above program only prints five numbers after the decimal. It can process it but when I print to screen, 1.1111113 becomes 1.11111.
Is this normal?
Need a little help with Stroustrup's Drills from Programming Principles and Practice - C and C++ - Codecall
回答のおかげで、ドリル5の疑問が解決した。
精度の指定
桁数が多いと表示の際に丸められてしまう問題は、値の精度を指定できるsetprecision関数を使えばよい。
- C++ : Reference : IOstream Library : manipulators http://www.cplusplus.com/reference/iostream/manipulators/
setprecisionの使い方については、次のページも参考になった。
- cp_C++言語(予備知識) http://www.page.sannet.ne.jp/mtoga/lang/cp/bih-p_09.htm
値の出力前に、setprecisionで精度10桁を指定することにした。
絶対値の取得
ついでに、絶対値を返してくれるfabs関数を覚えた。
- C++ : Reference : C Library : cmath (math.h) : fabs http://www.cplusplus.com/reference/clibrary/cmath/fabs/
前回の回答では自分でIsAlmostEqual関数を書いていたけど、fabs関数に置き換えた。
回答修正版
#include "../../std_lib_facilities.h" int main(){ double n = 0; double m = 0; cout << "数字を2つ入力する。「|」を入力したら終了する。\n"; while(cin >> n >> m){ if(cin.fail()){ cout << "input error. \n"; break; } if(n == '|' || m == '|'){ break; } cout << setprecision(10); if(n < m){ cout << "the smaller value is: " << n << "\nthe larger value is: " << m << endl; }else if(m < n){ cout << "the smaller value is: " << m << "\nthe larger value is: " << n << endl; } if(n == m){ cout << "the numbers are equal" << endl; }else if(fabs(n - m) < (1.0/10000000)){ cout << "the numbers are almost equal" << endl; } } return 0; }
実行例。
数字を2つ入力する。「|」を入力したら終了する。 9.999999999 9.99999999 the smaller value is: 9.99999999 the larger value is: 9.999999999 the numbers are almost equal 9.9999999999 9.999999999 the smaller value is: 9.999999999 the larger value is: 10 the numbers are almost equal
わーい。
ヒントの探し方
鈍器本のドリルが解けなくて困った時は、「"Programming Principles and Practice Using C++" drill chapterx」(x=章番号)で検索するといろいろ捗る。「ストラウストラップのプログミング入門 ドリル x章」の検索結果は、まだ少ない。
何かずるい気もするけど、挑戦した後なら見てもOKということにする。
知識が増えればそれでいいし、挫折しないことが重要。