C. Carlier
C. Carlier

Reputation: 21

Having trouble writing an equation with complex exponents in C#

I have done some research and can't seem to find what I need. It may be an easy fix but I am stumped. I am trying to write and equation in c# and it is returning a NaN value for me and I don't know why. I have posted my code below as well as a picture of the original equation. Any help would be appreciated, I don't believe I am entering the equation correctly.

static void Main(string[] args)
    {
        int playerLevel;
        double experience = 1;
        WriteLine("Please Enter Your Current Level: ");
        playerLevel = Convert.ToInt32(ReadLine());
        try
        {
            experience = 1 / 8 * (Math.Pow(playerLevel, 2) - playerLevel + 600 * ((Math.Pow(2, Convert.ToDouble(playerLevel/7)) - Math.Pow(2, Convert.ToDouble(1/7))) / (Math.Pow(2, Convert.ToDouble(1/7)) - 1)));
            WriteLine("Your current Experience is: " + experience);
        }
        catch (Exception err)
        {
            WriteLine(err.Message);
            throw;
        }
        ReadKey();
    }

Original Equation

Upvotes: 1

Views: 169

Answers (2)

Wyck
Wyck

Reputation: 11730

This code is the culprit: / (Math.Pow(2, Convert.ToDouble(1 / 7)) - 1)

  • 1/7 is 0.
  • 2^0 is 1
  • 1 - 1 is 0
  • you're dividing by zero, giving you NaN.

Consider just writing 1.0/7.0 instead of Convert.ToDouble(1 / 7)

The part that likely tripped you up is that 1/7 is zero because it's integer division. 1 is an integer and 7 is an integer, so the / will use integer division, giving 0.

Upvotes: 7

Lemon Sky
Lemon Sky

Reputation: 697

Add ".0" or "d" after all your numbers to indicate that they are not integers. For example, write "1.0" instead of "1".

Upvotes: 0

Related Questions