如何将以下C#代码从使用while循环更改为for循环? [英] How do I change the following C# code from using a while loop to for loop?

查看:99
本文介绍了如何将以下C#代码从使用while循环更改为for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int x = 1;

while(x< 10)

{

Console.Write(x);

x ++;

}



我尝试过:



int x = 1;

for(int x = 1; i< = 10; i ++)

{

Console.Write(x);

x ++;

}

int x = 1;
while(x < 10)
{
Console.Write(x);
x++;
}

What I have tried:

int x = 1;
for(int x = 1;i<=10;i++)
{
Console.Write(x);
x++;
}

推荐答案

发布的代码根据我的尝试不应该工作,因为你声明 x 两次并使用但不声明 i 。这段代码怎么样:



The code posted under what I have tried should not work because you declare x twice anduse but not declare i. How about this code:

for(int x = 1;x<10;x++)
{
  Console.Write(x);
}


你在这里申报x两次,一次在这里:

You are declareign x twice, once here:
int x = 1;

一旦在这里:

for(int x = 1;i<=10;i++)

这不是一个好主意,因为编译器会告诉你:

That's not a good idea as the compiler will tell you:

A local variable named 'x' cannot be declared in this scope because it would give a different meaning to 'x', which is already used in a 'parent or current' scope to denote something else

你根本没有声明

然后就是结束条件,对于两个循环不同 - 你的新循环会执行额外的迭代,因为即使 i 等于10,它也会继续运行。 />
要更改此

And you don't declare i at all!
Then there is the ending condition, which isn't the same for the two loops - your new one would perform an extra iteration because it continues to run even when i is equal to 10.
To change this

int x = 1;
while (x < 10)
    {
    Console.Write(x);
    x++;
    }

for 循环,只需执行以下操作:

to a for loop, just do this:

for (int x = 1; x < 10; x++)
    {
    Console.Write(x);
    }


在for中将x设置为1,然后检查i是否为< = 10,然后递增i。



In the "for" you are setting x to 1, then checking if i is <= 10, then incrementing i.

int x = 1;
for(int x = 1;i<=10;i++)
{
Console.Write(x);
x++;
}





更改为





Change to

int x = 1;
for(int i = 1;i<=10;i++)
{
Console.Write(x);
x++;
}





或者你可以完全摆脱x





Or you could get rid of x altogether

for(int i = 1;i<=10;i++)
{
Console.Write(i);
}


这篇关于如何将以下C#代码从使用while循环更改为for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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