循环周问题 [英] question on loop weeks

查看:72
本文介绍了循环周问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

Hello

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
          int count = 52;
            for (int i = 1; i <= count; i++)
            {
                Console.Write("{0} {1,2}", "Week", i);
                Console.ReadLine();
            }

        }
    }
}


是的,我知道代码是错误的.

我正试图让它也一年一次每三周写一次.并可以像不需要在每一行中键入console一样来做到这一点.它看起来像这样:

第1周第3周第5周
第7周第9周第11周
依此类推,直到第51周


Yes, I know the code is wrong.

I''m trying to get it too write out every 3 week in a year. and can you do it like you dont need to type console for every line. its go to look something like this:

Week 1 week 3 week 5
week 7 week 9 week 11
and so on until week 51

推荐答案

尝试for (int i = 1; i <= count; i+=2)


确定,然后您要做的第一件事就是更改您的for循环:i ++仅增加1,而您希望增加2:
Ok, then the first thing you need to do is change your for loop: i++ only increments by one, and you want by two:
for (int i = 1; i <= count; i++)

成为:

for (int i = 1; i <= count; i += 2)


使其写得更少些会有点困难,但不是很多.您有两种方法:
1)不要使用WriteLine,而应使用Write.然后,在写了三组之后,写一个空白行.
2)将输出构建为字符串(或更好的StringBuilder),并在有三组时将其写入.

您的老师更喜欢哪个?到目前为止,您学习了哪门课程?
我得到这个来帮助我.


Making it write less often is slightly harder, but not a lot. You have two ways:
1) Don''t use WriteLine, use Write instead. Then after you have written three groups, write a blank line.
2) Build your output into a string (or better a StringBuilder) and write it when you have three groups.

Which would your teacher prefer? Which has your course covered so far?
"i get this to help me out.

int p= 0;
const int cols = 3;

p++;
if ( (p >= cols) && (p % cols == 0))
Console.WriteLine();


是的,这是学校的工作,但您不需要展示它"

我猜是这样! :laugh:

因此,您需要像上面显示的那样更改循环,然后合并两个代码片段:


and yes it is a school work but you dont need to show it"

I guessed it was! :laugh:

So, you need to change your loop as I showed above, then merge the two code fragments:

int count = 52;
int p= 0;
const int cols = 3;
string assembly = "";
for (int i = 1; i <= count; i += 2)
{
    assembly += string.Format("{0} {1,2}", "Week", i);
    p++;
    if ( (p >= cols) && (p % cols == 0))
    {
       Console.WriteLine(assembly);
       assembly = "";
    }
}
Console.WriteLine(assembly);


通常,我建议使用StringBuilder而不是string来执行此操作,但是如果您尚未遇到它们,请使用字符串-稍后请记住,通常这不是一个好主意,由于复杂的原因.
现在,您实际上是否需要变量"p"-可以摆脱它并获得相同的输出吗?


Normally, I would suggest doing this with a StringBuilder, rather than a string but if you haven''t met them yet, go with the string - just remember for later that it''s not normally a good idea, for complicated reasons.

Now, do you actually need the variable "p" - can you get rid of it and get the same output?


这篇关于循环周问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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