|
-
June 4th, 1999, 10:28 PM
#1
Number Crunching
Hi,
I'm trying to duplicate a routine I have in VB to VC++. It's a loop that checks to see if a floating point number becomes a whole number.
In VB I used a while loop that checked for the decimal point using the InStr function. In the body of the loop I would alternate the VAL and STR functions to change the number from a string to a real number. With a multiplication routine inside the loop, eventually the floating point number would reach a whole number without any fractional amount left over,the STR conversion of the whole number would drop the decimal off of the string and would terminate the loop.
All the conversion routines in C++ seem to pad zeros to the right of the decimal point of a floating point number if it becomes a whole.
Does anyone know of a way to reproduce the effect I had in VB so I can drop out of a loop if a number has no fractional amount left over?
Steve Palmer
-
June 5th, 1999, 01:00 AM
#2
Re: Number Crunching
You should just use %1. For example assume num is the int variable you are working with, you would simply use something like this
if (num%1){
/ /not a whole number continue on
}
else{
// is a whole number stop
}
Applying %1 returns 0 if the number is whole and the remainder (anything after the decimal) if it's not. This method should work in all languages and is proably a lot more effeciant then converting it back and forth between a string and a number.
-
June 5th, 1999, 04:37 PM
#3
Re: Number Crunching
I don't think the % operator will work because it requires integer operands
One possibility is to use floor or ceil and a subtraction to determine what
the fractional component of a number is. Something like this :
if( dblval < 0.0 )
fraction = ceil( dblval ) - dblval;
else
fraction = dblval - floor( dblval );
For a dblval of 3.001, fraction is 0.001.
For a dblval of -4.02, fraction 0.02.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|