This question has already been answered:
- Specification output double using cout 1 response
Noticed the strange behavior of type double.
Question:
There is a code:
double miles; double km; while(true) { cout << "\nEnter distance in miles: "; cin >> miles; if(miles <= 1 && miles > 0) { km = miles * 1.609; cout << "Your " << miles << " mile in kilometers: " << km << endl; } if (miles > 1) { km = miles * 1.609; cout << "Your " << miles << " miles in kilometers: " << km << endl; } if (miles == 0) { cout << "\nOh, no, man. Enter something but 0\n"; } Checked all the options if - works as intended. But when I enter a symbol instead of a number, the last condition with zero is satisfied. But this is not the worst. In this case, the inscription Oh, no, man. Enter something but 0 Oh, no, man. Enter something but 0 appears more than once, if you enter exactly 0, but it appears constantly (as if in an infinite loop). That is, the while(true) works, but for some reason, after entering a character, it stops requesting input from the user. What is the reason?
ps: I know that while (true) is a wildly wrong instruction and should be avoided, I just didn’t want to restart the program each time to check the new value.
pss: if you type int instead of double, then the same, apparently, this is not a feature of exactly double. By the way, if you enter a very long number, then the endless loop also begins.
cout.precision()with the required number of characters. Just keep in mind that the value offloat, normalized to1,...can not be smaller than 1/2 ^ 23. In your case, the maximum accuracy is 1/2 ^ (23 - 4) = 1/524288 = 0.0000019073 (if I do not confuse anything, since 12 is about 2 ^ 4, that is, it takes 4 bits of mantissa). - ߊߚߤߘ