Returning a single character from a string, returns as a int?(bit operate
#1

So yeah, I have this stock

pawn Код:
stock GetFirstNumber(number)
{
    new
        number_str[12],
        bool: negative;
   
    if (number < 0) negative = true;
    valstr(number_str, number);
    return (negative) ? (number_str[1]) : (number_str[0]);
}
I pass it something between 1000 and 2000 and I get 49, I pass it something above 2000 and I get 50, and so forth. I was wondering why it's returning such strange numbers and if there's something wrong with the stock..

I've checked the integer i'm passing it, it's correct..
Reply
#2

This is because the textual representation of a number is different than the number itself. See here: http://www.asciitable.com/index/asciifull.gif
The textual representation of the number 2 is 50, which is exactly what you're describing. You need strval to reconvert it to the numerical value. Not sure if there's better way to do it.
Reply
#3

I should have remembered this from the awful time I spent with VB, thank you very much.
Reply
#4

Operations on strings are quite slow, just do something like
pawn Код:
stock FirstDigit(n) {
    new
        digit = 0;
       
    n *= n < 0 ? -1 : 1;

    do {
        digit = n % 10;
        n /= 10;
    } while (n > 0);
   
    return digit;
}
Reply
#5

Would you mind explaining the code though?
Reply
#6

Sure thing:
pawn Код:
stock FirstDigit(n) {
    new
        digit = 0;
       
    //First thing - get the absolute value of n
    //(in fact that's a little better version)
    if(n < 0) n = -n;

    do {
        //Get the modulus of n, returning last digit
        //(we can't jump straight to first though :c)
        //So for 1245 it will be 5
        digit = n % 10;
       
        //Remove last digit (it's an integer, so it doesn't have fractions - insta flooring)
        //1245 => 124
        n /= 10;

        //Do so until there are no more digits left
    } while (n > 0);
   
    return digit;
}
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)