Tell me how to correctly put the type check: If the number res is integer
if (...) { ...; } Can eat standard?
Tell me how to correctly put the type check: If the number res is integer
if (...) { ...; } Can eat standard?
I haven't used C ++ for a long time, but as far as I remember, such things are done through the ghost operator:
dynamic_cast All other ghosts are something inherited from С In С++ there is an operator for each case.
For checking built-in types, this approach will not work. Different compilers have macros, for example, __typeof__ . They are specific to a particular compiler.
C++ Supports trimmed RTTI. It is possible to use only the language features of C++ , look at this code:
#include <stdio.h> #include <typeinfo.h> using namespace std; int main(){ int a = 10; printf("Type is %s", typeid(a).name()); }; Something like this:
float a; if ( (float)( (int) a ) === a ) //Целое It is better to always use double (float only for storage in large arrays).
double r; if (r == (long long)r) // Целое Or so:
if(floor(value) == value) ... For this you need to connect math.h.
Some may argue that comparing floating-point numbers for equality is wrong. But if it were always wrong, the compiler would not allow this in principle. In this case, integers can be represented exactly in double. The operations of addition, subtraction and multiplication for integers will also give integers, since they do not introduce rounding errors. For the numbers specified manually or obtained in this way, the verification above will work correctly. If you still need to check that the number is an integer within a certain error eps (for example, 0.000001), you can use the following test:
if(abs(floor(value + 0.5) - value) < eps) ... Or if the round function is available in the used version of the standard library:
if(abs(round(value) - value) < eps) ... These two options use rounding to the nearest integer so that the difference between this and the original number is in the interval (-0.5; 0.5), and not [0; 1), as in the case of rounding to a smaller one.
Source: https://ru.stackoverflow.com/questions/64425/
All Articles