none
Why is this statement returning 0? RRS feed

  • Question

  • I have a method that populates a list with prime numbers. I'm outputting to the debug window to see the progress of it as it happens like so:

    public static void PopulatePrimeList()
    {
        Debug.WriteLine("Entering PopulatePrimeList().");
    
        // Manually add the first prime number.
        PrimeList.Add(2);
        Debug.WriteLine(2);
    
        for (short checkValue = 3; checkValue <= short.MaxValue && checkValue > 0; checkValue += 2)
        {
            if (IsPrime(checkValue))
            {
                PrimeList.Add(checkValue);
                Debug.WriteLine($"Populating PrimeList {checkValue / short.MaxValue * 100}%: Adding {checkValue}.");
            }
        }
    
        Debug.WriteLine("PrimeList populated.");
    }
    

    The part in question is this: 

    {checkValue / short.MaxValue * 100}

    it always returns 0 and I can't tell why. Does anyone know?

    Any and all help would be appreciated.

    Tuesday, March 3, 2020 2:16 PM

Answers

  • Because it is using short data type. You need to use double for example $"{Convert.ToDouble(checkValue) / short.MaxValue * 100}".

    • Marked as answer by Integrater Tuesday, March 3, 2020 3:28 PM
    Tuesday, March 3, 2020 2:36 PM