如何在下面的输出中创建代码 [英] How do create code in below output

查看:72
本文介绍了如何在下面的输出中创建代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

12345

234

3



这个结果如何获得单循环和

用于获得结果的条件和逻辑



我尝试过:



for(int i = 1; i< = 5; i ++)

{

console.write(i);

}

for(int j = 1; j< = 5; j ++)

{

if(j == 1 | | j == 5)

{

console.write();

}

else

{

console.write(j);

}



}

for(int k = 1; k< = 5; k ++)

{

if(k == 3)

console.write(k)

else

console.write();

}

12345
234
3

how to this result get in single loop and
which condition and logic used to get result

What I have tried:

for(int i=1;i<=5;i++)
{
console.write(i);
}
for(int j=1;j<=5;j++)
{
if(j==1||j==5)
{
console.write(" ");
}
else
{
console.write(j);
}

}
for(int k=1;k<=5;k++)
{
if(k==3)
console.write(k)
else
console.write(" ");
}

推荐答案

首先,这不起作用,因为您需要明确说明何时到达行尾:call Console.WriteLine 在行之间打破它们。

并记住C#是区分大小写的:缺点ole.write 不同.Console.Write

这是你的作业,所以我不会去给你代码!但是一些提示并不是问题:

你不能在单循环中真正做到这一点 - 你至少需要两个循环:一个打印每一行,一个打印该行的内容。也就是说,假设您必须具有灵活性并允许除5以外的其他值,则行的宽度应为。如果没有,它是微不足道的,你不需要循环:

First off, that won't work because you need to explicitly say when you have reached the end of a line: call Console.WriteLine between the lines to "break" them in the output.
And remember that C# is case sensitive: console.write is not the same as Console.Write
This is your homework, so I'm not going to give you the code! But a few hints isn;t a problem:
You can't really do that in a "single loop" - you need two loops as a minimum: One to print each line, and one to print the contents of that line. That is, assuming you have to be flexible and allow for other values than 5 as the number of characters wide the lines should be. If not, it's trivial, and you don't need a loop:
Console.WriteLine("12345");
Console.WriteLine(" 234 ");
Console.WriteLine("  3  ");

但提交这不会让你获得好成绩! :笑:

你真正想做的是有两个循环,一个在另一个里面。

外循环写每一行:

But submitting that won't get you a good grade! :laugh:
What you actually want to do is have two loops, one inside the other.
The outer loop writes each line:

for (int i = 0; i < numberOfLines; i++)
   {
   ...
   Console.WriteLine();
   }

在里面你有第二个循环来写行。

这实际上非常简单:你需要做的就是为字符数循环在线上减去行号,并检查循环索引。如果它小于行号,则打印一个空格。否则,打印索引值加一。

试一试:你会明白我的意思!

And inside that you have a second loop which writes the line.
That's actually pretty easy: all you need to do is loop for the number of characters on the line minus the line number, and check the loop index. If it's less than the line number, print a space. Otherwise, print the index value plus one.
Try it: you'll see what I mean!


这篇关于如何在下面的输出中创建代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆