如何在c#中打印二进制数的三角形

时间:2015-09-28 08:00:33

标签: c# visual-studio

我需要在此代码段中添加二进制数逻辑。我只是无法理解如何实现二进制数,我只能添加01 s,但这似乎不正确

namespace Star_Pyramid
{
class Program
{
    static void Main(string[] args)
    {
        int num;
        Console.WriteLine("enter level");
        num = Int32.Parse(Console.ReadLine());
        int count = 1;

        for (int lines = num; lines >= 1; lines--)
        {

            for (int spaces = lines - 1; spaces >= 1; spaces--)
            {
                Console.Write(" ");

            }
            for (int star = 1; star <= count; star++)
            {
                Console.Write("*");
                Console.Write(" ");

            }
            count++;

            Console.WriteLine();
        }
        Console.ReadLine();
    }
    }
}

1 个答案:

答案 0 :(得分:2)

您可以使用modulo%

  c = star % 2;        // will print first the '1'
  c = (star + 1) % 2;  // will print first the '0'
    int num;
    Console.WriteLine("enter level");
    num = Int32.Parse(Console.ReadLine());
    int count = 1;
    int c = 0;

    for (int lines = num; lines >= 1; lines--)
    {

        for (int spaces = lines - 1; spaces >= 1; spaces--)
        {
            Console.Write(" ");

        }
        for (int star = 1; star <= count; star++)
        {
            c = star % 2; //this will return 1 if the value of star is odd then 0 if even
            Console.Write(c);
            Console.Write(" ");

        }
        count++;

        Console.WriteLine();
    }
    Console.ReadLine();

<强> VIEW DEMO