I have to use a variable of type double to store and manipulate a value for an amount of years. This means I have to ensure that the data input by the user is an integer. The program will accept a non-integer value, but I want it to continue reprompting the user when a non-integer is entered. I thought I had this solved, but it does not work for some reason. Here is the code:

do
{
userinputfunction(x,y,z,etc...)
} while((loanYears <= 1) && (loanYears >= 100) && ((floor(loanYears)) != loanYears));

However, the do ... while loop does not work as planned! Everything but the last part works. [i.e. - ((floor(loanYears)) != loanYears))] The last part is supposed to validate the users input as an integer.

## All 4 Replies

floating point numbers always have a degree of imprecision. A floating point value will never be equal to a whole number. You should check to see if it is within an acceptable epsilon from a whole number (or fractional value, if such a situation were to arise). (loanYears <= floor(loanYears) + epsilon)

>The program will accept a non-integer value, but I want it to continue reprompting the user when a non-integer is entered.
You can use fgets and then parse trought the string checking is it number or not in a do...while loop. But you need to change the logic of input

I have to use a variable of type double to store and manipulate a value for an amount of years. This means I have to ensure that the data input by the user is an integer. The program will accept a non-integer value, but I want it to continue reprompting the user when a non-integer is entered. I thought I had this solved, but it does not work for some reason. Here is the code:

The first step in solving the problem is to properly understand the problem domain and the prog requirements. IF you just want to accept and manipulate a value for amout of years why not just use unsigned long instead of going to the trouble of using a floating point variable which always ditches the programmer when it comes to comparing it with some other floating number.

Do a second check on you logic, as suggested by Mr. Andor. It would definately solve your problem. Otherwise if you still want to stick to floating point types then you have to follow the advice given by Mr. Infarction which involves deciding on a tolerance value or the deviation value by which your two floating point numbers can differ.

HOpe it helped, bye.

If you must use a double...for whatever reason...you can use

if (loanYears - static_cast<int>(loanYears) != 0)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.