Home > Net >  Why do i get question mark in console instead of a double value / NaN and what does it mean?
Why do i get question mark in console instead of a double value / NaN and what does it mean?

Time:08-04

So i wrote a recursive function for Pow() and the return value for 2^int.MaxValue/2 is "?". Atleast that is written into the Console. Why is that?

(yes i know recursion bad... but that was my assignment)

Code:

public static double Pow(double x, int y)
    {
        if (y > 0)
        {
            if (y == 1)
            {
                return x;
            }
            return Pow(x, y / 2) * Pow(x, (y   1) / 2);
        }
        else if (y == 0)
            return 1;
        else
        {
            if (y == -1)
            {
                return 1 / x;
            }
            return Pow(x, y / 2) * Pow(x, (y - 1) / 2);
        }
    }

Main:

public static void Main()
    {
        Console.WriteLine($"3^3 = {MyMath.Pow(3, 3)}");
        Console.WriteLine($"3^2 = {MyMath.Pow(3, 2)}");
        Console.WriteLine($"3^1 = {MyMath.Pow(3, 1)}");
        Console.WriteLine($"3^0= {MyMath.Pow(3, 0)}");

        double d1 = MyMath.Pow(2, int.MaxValue / 2);
        double d2 = MyMath.Pow(2, int.MaxValue);

        long l1 = BitConverter.DoubleToInt64Bits(d1);
        long l2 = BitConverter.DoubleToInt64Bits(d2);

        string s1 = Convert.ToString(l1, 2);
        string s2 = Convert.ToString(l1, 2);

        Console.WriteLine($"Pow: 2^{int.MaxValue / 2}={d1}");
        Console.WriteLine($"Pow: 2^{int.MaxValue}={d2}");
        Console.WriteLine($"Pow: 2^{int.MaxValue / 2}={l1}");
        Console.WriteLine($"Pow: 2^{int.MaxValue}={l2}");
        Console.WriteLine($"Pow: 2^{int.MaxValue / 2}={s1}");
        Console.WriteLine($"Pow: 2^{int.MaxValue}={s2}");
    }

Output:

3^3 = 27
3^2 = 9
3^1 = 3
3^0= 1
Pow: 2^1073741823=?
Pow: 2^2147483647=NaN
Pow: 2^1073741823=9218868437227405312
Pow: 2^2147483647=-2251799813685248
Pow: 2^1073741823=111111111110000000000000000000000000000000000000000000000000000
Pow: 2^2147483647=111111111110000000000000000000000000000000000000000000000000000

Cpu: i5-7500 3.40GHz, 4cores

CodePudding user response:

It's trying to display the "infinity" symbol, .

By default, the console uses the 850 code page or the 437 code page, which don't support that character.

On my system, by default that's displayed as 8 in a .Net Framework console app (which I find rather annoying), but on your system it appears to just display ? to show that it's not a supported character.

You should be able to fix this by adding the following to the start of your Main() method:

Console.OutputEncoding = System.Text.Encoding.Unicode;
  • Related