显示二进制数三角形的正确代码????? [英] correct codes for displaying binary numbers triangle?????
问题描述
我正在尝试写一个C sharp程序来显示这样的东西
1
01
101
0101但是我很难做到这一点。到目前为止我只能这样显示
1
10
101
1010.我知道这对你们很简单..我需要帮助......任何人???在此先感谢...
这是我到目前为止的编码..........
I am trying to write a C sharp program to display something like this
1
01
101
0101 but i'm having trouble doing that.So far i can display only like this
1
10
101
1010. i know its simple for you guys..i need help...anyone??? thanks in advance...
Here is my coding so far..........
static void Main(string[] args)
{
String input;
int i, j, ran;
Console.WriteLine("Enter the Range:");
input = Console.ReadLine();
ran = Convert.ToInt16(input);
for (i = 1; i <= ran; i++)
{
for (j = 1; j <= i; j++)
{
if (j % 2 == 0)
{
Console.Write("0 ");
}
else
{
Console.Write("1 ");
}
}
Console.WriteLine();
}
Console.Read();
}
[已添加代码格式]
[Added code formatting]
推荐答案
由于您的代码有效很好地除了1和0向后退出,用j = i开始内循环然后每次减少1,停在1?
ie
Since you code works nicely except that the 1's and 0's come out backwards, howabout starting the inner loop with j = i and reduce it by 1 each time, stopping at 1?
ie
for (j = i; j >= 1 ; j--)
{
if (j % 2 == 0)
{
Console.Write("0 ");
}
else
{
Console.Write("1 ");
}
}
我没有尝试过,只是一个想法。 :)
转换为代码块以保留格式[/ edit]
干杯! :)阿里[/ edit]
I haven't tried it, just an idea for you. :)
[edit]Converted to code block to preserve formatting[/edit]
[edit]Cheers! :) Ali[/edit]
艾莉森打败了我!只是她的解决方案的一个小改进 - 你不需要if条件:
Alison beat me to it! just a small improvement to her solution - you don't need the if condition:
for (int j = i; j > 0; j--)
{
Console.Write("{0} ", j & 1);
}
Console.WriteLine();
您实际上不需要循环的内部
。所有发生的事情是前一个字符串前面有一个0或1。所以你可以这样做。
You don't actually need the inner
for
loop. All that is happening is that a 0 or a 1 is being prepended to the previous string. So you can do this.
StringBuilder sb= new StringBuilder();
int count = 5;
for (int t = 1; t <= count; t++)
{
sb.Insert(0, t & 1);
Console.WriteLine(sb);
}
这篇关于显示二进制数三角形的正确代码?????的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!