如何在C中打印二进制数字的三角形#
问题描述:
我需要将二进制数字逻辑添加到此代码段中。我只是不能换我周围的头如何实现二进制数,我可以只添加0
S和1
秒,但似乎并没有被正确如何在C中打印二进制数字的三角形#
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();
}
}
}
答
可以使用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();
+0
就是上面提到的线,什么是0:1;意思? –
+0
交替打印1和0 ..试试看演示 –
+0
哦,我明白了。所以0:1;有点像Console.Write(“0”)和Console.Write(“1”); ? –
请解释你的意思是“添加二进制数逻辑” –
@SamiKuhmonen我需要打印由二进制数组成的三角形 –
@MohammadQasim第一个内部'for'可以替换为'Console.Write(new String ('',lines - 1));' –