public string PrintRandomShape(int length, int width)
{
string output = "";
for (int rows = 1; rows <= length; rows++)
{
if (rows == 1)
{
for (int cols = 1; cols <= width; cols++)
output += "0";
}
else
{
for (int cols = 1; cols <= width / 2; cols++)
output += " ";
output += "*";
output += "\n";
}
}
return output;
//expected output is
000000 *
*
*
*
出于某种原因,星号在那边
答案 0 :(得分:1)
你在else子句中做的第一件事就是添加一个星号,但你永远不会给它一个新行,最简单的解决方法是在if子句中的循环之后添加你的新行
for (int cols = 1; cols <= width; cols++)
output += "0";
output += "\n";
答案 1 :(得分:1)
虽然这可能是学习使用for循环的一个分配,但是还有一些其他方法可以用来创建这个结构,只有1个for循环,nl:
using System;
using System.Text;
public class Program
{
public static void Main()
{
Console.WriteLine( CreateRandomShape(10, 5) );
}
public static string CreateRandomShape(int width, int height) {
StringBuilder output = new StringBuilder();
for (int y = 0; y < height; y++) {
if (y == 0) {
output.AppendLine(new String('0', width));
} else {
output.AppendLine(new String(' ', width / 2) + "*");
}
}
return output.ToString();
}
}
这里重复值由字符串构造函数处理,取一个char并且需要重复给定char的次数。 StringBuilder为每个输出添加一个新行(通过使用Environment.NewLine(类似于\n
字符,但特定于操作系统)和output.ToString()然后输出字符串内容
正如Sayse提到的那样,你在第一行的当前解决方案中得到了明星,原因很简单,因为你没有追加换行符。你可以像解决这个问题一样在你的解决方案中处理它
public string PrintRandomShape(int length, int width)
{
string output = "";
for (int rows = 1; rows <= length; rows++)
{
if (rows == 1)
{
for (int cols = 1; cols <= width; cols++)
output += "0";
}
else
{
for (int cols = 1; cols <= width / 2; cols++)
output += " ";
output += "*";
}
output += "\n"; // this will always append the new line, in both cases...
}
return output;
}
答案 2 :(得分:0)
这是因为for循环中缺少NewLine
for (int rows = 1; rows <= length; rows++)
{
if (rows == 1)
{
for (int cols = 1; cols <= width; cols++)
output += "0";
output += "\n";
}
else
{
for (int cols = 1; cols <= width / 2; cols++)
output += " ";
output += "*";
output += "\n";
}
}
答案 3 :(得分:0)
如果你真的不想要它们,那么试着避免复杂的构造(你需要调试它们)。在您的特定任务中,您所要做的就是打印
length
- 2次)就这样做,请不要将这些实现塞进单个循环中:
public string PrintRandomShape(int length, int width) {
// For public methods validate its arguments
if (length <= 0)
throw new ArgumentOutOfRangeException("length");
else if (width <= 0)
throw new ArgumentOutOfRangeException("width");
// When creating a string (esp. in a loop) use StringBuilder
// length * width + 2 * length - optimization; but it's not that required
StringBuilder sb = new StringBuilder(length * width + 2 * length);
// Top Line: width '0''s
sb.Append('0', width);
// Body, try avoiding complex loops with conditions
// length - 2 (-2 : top + bottom lines == 2) lines of
// '*' + [width - 2] spaces + '*' strings
for (int i = 0; i < length - 2; ++i) {
sb.AppendLine();
sb.Append('*');
if (width >= 2) {
sb.Append(' ', width - 2);
sb.Append('*');
}
}
// Bottom Line width '0''s from new line if total width is greater than 2
if (length >= 2) {
sb.AppendLine();
sb.Append('0', width);
}
return sb.ToString();
}
答案 4 :(得分:-1)
由于它是一个特殊字符,\ n引起了这种情况。这是一个你不想要的输入。如果你删除它,该程序应该工作。请让我知道:)