简体   繁体   English

如何使用While和Do While在标签中显示前100个偶数? C#

[英]How to show in a label first 100 even numbers using While and Do While ? c#

Actually i have a button to display the first 100 even numbers using For 实际上,我有一个按钮可以使用For显示前100个偶数

    int a = 100;
        int res = 0;
        int i;
        string npares = "";
        for (i = 0; i <= a; i++)
        {
            if (i % 2 == 0)
            {
                res = res + i;
                if (i < a)
                    npares += i + ",";
                else
                    npares += i;
            }


        }
        LBLstatus.MaximumSize = new Size(200, 0);
        LBLstatus.Text = npares;

But i need to make the same with more two buttons using While and Do While , how i can make this ? 但是我需要使用While和Do While用两个以上的按钮进行设置,如何做到这一点?

EDIT >>>>>> 编辑>>>>>>

Using while i got this way : 我用这种方式使用时:

int a = 100;
        int i = 0;
        string npares = "";
        int res = 0;

        while (i <= a)
        {
            i++;
            if

                (i % 2 == 0)
            {
                res = res + i;
                if (i < a)
                    npares += i + ",";
                else
                    npares += i;
            }
            LBLstatus.Text = npares;

(This answer shows the relationship between constructs, but does not otherwise attempt to provide a solution.) (此答案显示了构造之间的关系,但未尝试提供解决方案。)


The construct 构造

for (init;cond;post)
{
    body;
}

can be generally rewritten as / considered equivalent to 通常可以重写为/认为等同于

init;
while (cond) {
    body;
    post;
}

On the other hand a do-while has no analogous simple for form, because it delays evaluation of cond until after the body has been executed once, but it can be written as 另一方面,do-while for形式上没有类似的简单之处,因为它会将对cond评估延迟到执行完主体一次之后,但是可以写成

for (init;;post) {
    body;
    if (!cond) break;
}

Using Take 使用Take

List<int> ints;

List<int> positiveInts = ints.Where(i => i % 2 == 0).Take(100).ToList();

Using Aggregate 使用Aggregate

List<int> ints;

string positiveInts = ints.Where(i => i % 2 == 0).Take(100).Select(i => i.ToString()).Aggregate((a,b) => b += String.IsNullOrEmpty(b) ? a : "," + a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM