Testing for Whole Numbers

Started by
1 comment, last by ApochPiQ 11 years, 8 months ago
How can I test if a certain expression evaluates to a specific data type? For Instance:

int i = rand%10+1;
if(i/3 == int)
do this
Advertisement
You're doing it right there in your code (just above the if statement). See that % operator? That's the modulus operator. Simplified explanation, a % b tells you the remainder when you divide a by b, and if the remainder is zero, a is in fact a multiple of b, and the result of a / b is an integer. So you would just do:

if (i % 3 == 0)
// i is divisible by 3, and thus i / 3 is an integer
[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]
Depends on the language you're using.


In C, C++, C#, and Java (my best guesses from the snippet you posted) values do not change types at runtime. So if you write this code:

int foo = [some expression];

Then foo is an integer, and always will be. If you try to assign anything else to it, you either get a compiler error, or you get the integer part of whatever number you tried to assign, if you use a cast.

If you're talking about a different language, which actually does support "dynamic types" (i.e. types of variables/values can change at runtime) then you'll need to specify the language, as they all differ in how you test for a specific type.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

This topic is closed to new replies.

Advertisement