Hi all, in one part of the progtam I need to stop user from entering a number with more then 1 decimal place. So 1.1 is ok but 1.15 is not. I have no clue how to do it (whot kind of condition wil i put in?
Thank you in advance
1 2 3 4 5 6 7 8
for (unsignedshort a = 1; a <= numJudges; a++){
do {
cout << "\n\n\tEnter score from judge number " << a << " : ";
cin >> score;
if (score < 0 || score > 6)
cout << "\n\n\tERROR! Score must be between 0 and 6." << endl;
}
while (score < 0 || score > 6);
It actually works with many decimal number.
I couldn't use your previous ideas 'cos I am true beginner, we only use #include <iostream> in class. I'm suppose to be able make this program with the little I know...
Thanks so much for your help.
I think it's better to do the tiny amount of math in your program rather than incuring the extra expense of converting the entire number to a string.
1 2 3
if (trunc(x*10) != x*10) {
cout << "one decimal only please.\n";
}
Sure do it that way if you don't care about precision or accuracy. Some numbers like 4 or 5 could be represented as like 3.999999999 or 4.99999999 or even 4.000001 or 5.0000001 so those would show up as invalid when in fact if you read it as a string they would be valid.
Sure do it that way if you don't care about precision or accuracy. Some numbers like 4 or 5 could be represented as like 3.999999999 or 4.99999999 or even 4.000001 or 5.0000001 so those would show up as invalid when in fact if you read it as a string they would be valid.
4 or 5 would represented exactly but your point is valid if there's a non-zero value after the decimal: when dealing with floating point numbers you normally need to consider rounding errors.
If they are integers they are represented exactly. If they are floating point (float or double) then that is not guaranteed. This is the same reason that
1 2 3 4
int a = 5;
double b = 5.0;
std::cout << (a == b ? "Equal" : "Not Equal") << std::endl;
will result in Not Equal (more than likely it may depend on compiler) and why you can't compare floating points with the == operator effectively.
on the other hand is working most of the times, as in it will always show error when there is more than one decimal place, but it also shows error with 4.6 and few other numbers that shouldn't be errors