ストラウストラップのプログラミング入門(6) 第4章ドリル(未完了)
『ストラウストラップのプログラミング入門』を読む。今日は4章のドリル。まだ終わってない。
わからないことを2つメモする。
ドリル1
(ループを繰り返すたびに)2つのint型の値を読み取り、それらを表示するwhileループで構成されたプログラムを記述する。'|'が入力されたらプログラムを終了する。
こんにちは、バッファ問題。
#include "../../std_lib_facilities.h" int main(){ int n = 0; int m = 0; cout << "数字を2つ入力する。「|」を入力したら終了する。"; while(cin >> n >> m){ if(cin.fail()){ cout << "input error. \n"; break; } if(n == '|' || m == '|'){ break; } cout << n << '\t' << m << '\n'; } return 0; }
複数の数値を空白区切りで入力すると、Enterを入力した時点で、前から2つずつ数値が出力される。奇数個の数値を与えた場合、最後の1つの数値がバッファに溜まる。
本当は、cinで数値が2つ入力された時点で、それらを出力し、かつバッファをクリアしたい。
けど、ストリームを開いて入力値を読み取り続けている時に、同時にその内容を監視するなんて、こういう感じで書いてる限りムリそう。
cin.clear()とかcin.ignore()とか見てみたけど、これらはエラー処理で使うものであって、逐次の入出力を実現するために使うものではなさげ。
そもそも「ループを繰り返すたびに2つの値を読み取る」という課題が曖昧だから、これはこれでいいんかなぁ。
ドリル6で、値を1つずつ読み取るように変更する課題があるので、ひとまず保留に。
ドリル5
2つの数字の差が1.0/10000000未満である場合に、どちらが大きくてどちらが小さいかを書き出した後、the numbers are almost equalを書き出すようにプログラムを変更する。
桁数が多いと、表示の際に丸められてしまう。
#include "../../std_lib_facilities.h" bool IsAlmostEqual(double x, double y){ bool result = false; double big = x; double small = y; if(x < y){ big = y; small = x; } if(big - small < (1.0/10000000)){ result = true; } return result; } int main(){ double n = 0.0; double m = 0.0; cout << "数字を2つ入力する。「|」を入力したら終了する。\n"; while(cin >> n >> m){ if(cin.fail()){ cout << "input error. \n"; break; } if(n == '|' || m == '|'){ break; } if(n < m){ cout << "the smaller value is: " << (double)n << "\nthe larger value is: " << (double)m << endl; }else if(m < n){ cout << "the smaller value is: " << (double)m << "\nthe larger value is: " << (double)n << endl; } if(n == m){ cout << "the numbers are equal" << endl; }else if(IsAlmostEqual(n, m)){ cout << "the numbers are almost equal" << endl; } } return 0; }
実行結果。
数字を2つ入力する。「|」を入力したら終了する。
9.99999
10
the smaller value is: 9.99999
the larger value is: 10
9.99999999
10
the smaller value is: 10
the larger value is: 10
the numbers are almost equal
JavaのBigDecimalみたいな型があるんかな?
それとも文字に変換して出力するとか?
むむ。