简体   繁体   中英

How to check if variable is whole in C++ without a math library

I'm writing a little program for a beginner C++ class, I'm supposed to take an input (I'm using double, because I like to make things harder for myself) from a user and output whether it's prime or composite, and if it's composite, I need to output at least one number which the number is divisible by.

I have too much time on my hands so I'm going a little out of my way to make it harder. I'm trying to do everything without using anything but iostream. I've gotten most of it, but this bit is stumping me: How can I determine if a double is an integer without using a math library?(I found questions that had good solutions using math.h here, but nothing without it) I'd like to think there's a way to do it without writing fifty lines of code for something that seems so simple ...

You should probably not be doing any computations in floating point, but a simple way of testing whether a number has decimals or not is taking the floor and comparing it with the original. In C++ you can take the floor by converting to an int (assuming only positive numbers) and then converting back to double :

bool isWhole( double d ) {
   int whole = d;               // will round down to the nearest integer
   return (d-whole < epsilon);  // for a small enough epsilon
}

You can convert the double value to a suitably large integer type, then see if the two values are the same:

double d = /* whatever */
long long ival = d;
if (ival == d) {
    /* d holds integral value. */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM