Search code examples
c#integerdouble

my int thinks its a double, how do i change this?


im using an online compiler so maybe thats the reason that its not working.

so i set the TCoins int to 0

int TCoins = 0;

then after you defeat an enemy it adds to the int

TCoins = coins + TCoins;

then i made a shop system, so i check to see if you have the coin amount to be able to buy the item, then i subtract the coin amount needed to the coin amount you have, now for some reason it thinks its a double when i do this

if(Answer == "S" && TCoins >= (S + 1) * Math.Pow(10,(S+1)))
{
    TCoins = TCoins - (S + 1) * Math.Pow(10,(S+1));
    S++;
}

im new to coding, so i might be being dumb and not realising what the problem is.


Solution

  • Well, Math works with double and thus

    Math.Pow(10,(S+1));
    

    returns double result (for instance, if S == -2 we'll get 0.1). You can either cast:

    (int) Math.Pow(10,(S+1))

    or implement custom integer power:

    public static class MathI {
      public static int Pow10(int value) {
        if (value < 0 || value > 9)
          throw new ArgumentOutOfRangeException(nameof(value));
    
        int result = 1;
    
        for (int i = 1; i <= value; ++i)
          result *= 10;
    
        return result;
      }
    }
    

    And then use MathI.Pow10(S + 1) instead of Math.Pow(10,S+1)