今天无意中,在工作中发现以前对for循环的理解大错特错.
class Program
{
static string InStr = "ab";
private static string AddTo18(string str)
{
string th = str;
--------------------------------------------------------------------------------------------------------
下面为执行完for循环第一轮时的执行流程
--------------------------------------------------------------------------------------------------------
1,先执行i=str.length结果是2(因为instr是ab)
2,判断i<3,2<3是符合条件(注:如果不符合i<3,直接就退出for循环了)
//我以前的错误理解是执行完i<3后,会执行i++,
//实际是执行完i<3会执行oth+="0"
3,此时会执行for循环中的oth+="0",此时oth的结果由ab变成ab0
--------------------------------------------------------------------------------------------------------
下面为执行完for循环第一轮后的执行流程
--------------------------------------------------------------------------------------------------------
//执行完for循环中的代码块,会执行i++,而不是i<3
4,执行i++,此时i的结果为3
//执行完i++,会接着执行i<3的判断
5,执行i<3,3<3不成立.直接退出for循环,不会继续执行oth+="0"
for (int i = str.Length; i < 3;i++ )
{
oth += "0";
}
return oth.Substring(0, 18);
}
static void Main(string[] args)
{
Console.WriteLine(AddTo18(InStr));
Console.ReadKey();
}
}
一定要加深对于语法的理解.不然由此构成的复杂一些的程序就会弄晕人
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/9240380/viewspace-723150/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/9240380/viewspace-723150/