対ダブルでループ。私はそれがダブルスとintsのループで何かを持っていると思うが、私はよくわからない。は私が一見似たループ用の2つの異なる出力を取得する理由を把握しようとしていますint型
このコード出力4:
Current Cost: 1
Remaining: 9
Current Cost: 2
Remaining: 7
Current Cost: 3
Remaining: 4
Current Cost: 4
Remaining: 0
4 candies; 0 left over
このコード出力3:
double num = 1.0;
double cost;
int counter = 0;
for(cost = 0.1; cost <= num; cost += .1) {
counter +=1;
num -= cost;
}
cout << counter << endl;
編集:
これをこれは、このセクションの出力である
int num = 10;
int cost;
int counter = 0;
for (cost = 1; cost <= num; cost += 1){
counter += 1;
num -= cost;
}
cout << counter << endl;
thの出力ですデバッグしようとしたときのコードです:
Current Cost: 0.1
Remaining: 0.9
Current Cost: 0.2
Remaining: 0.7
Current Cost: 0.3
Remaining: 0.4
3 candies; 0.400000 left over
なぜ2つの違いがありますか?
デバッガでそれをフォローするか、各変数の値はいつでも –
にあるものを見ることができるようにループ内で出力文を入れて[注意してください。 'double'はあいまいすることができます。](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – user4581301
@MM私はすでに、まだ理由である、問題を導き出すことができなかったこと私はここでIより良いことを知っている人の助けを求めるために来た。 – Biggytiny