如何在for循环中输出序列最后一个数及循环执行次数?
修改代码以输出最后一个数字和循环执行次数
Hey there! Let's figure out how to tweak this C# code to get exactly what you need. First, let's quickly recap what the original code does:
int numOne = 50; for (int i = 0; i < numOne; i++) { Console.WriteLine(i); }
This loop runs 50 times (since i starts at 0 and goes up to 49, that's 50 total values) and the last number it prints is 49.
两种修改方案(任选其一即可)
方案1:直接利用变量numOne计算(最简单)
Since we already know the loop's logic relies on i < numOne, we can directly derive the results using numOne without extra variables:
int numOne = 50; for (int i = 0; i < numOne; i++) { Console.WriteLine(i); } // 输出序列最后一个数字 Console.WriteLine($"序列中的最后一个数字是: {numOne - 1}"); // 输出循环执行次数 Console.WriteLine($"for循环的执行次数是: {numOne}");
方案2:借助循环结束后的i值
If we declare i outside the loop, once the loop stops, i will equal numOne (because when i hits 50, the loop condition fails). We can use this value to calculate our results:
int numOne = 50; int i; // 把i声明在循环外 for (i = 0; i < numOne; i++) { Console.WriteLine(i); } // 最后一个数字是i-1(循环停止时i已经是50了) Console.WriteLine($"序列中的最后一个数字是: {i - 1}"); // 执行次数就是i的值(50) Console.WriteLine($"for循环的执行次数是: {i}");
为什么这样改?
- 循环执行次数:
istarts at 0, increments by 1 after each loop run, and stops wheniis no longer less thannumOne. That means it runs exactlynumOnetimes (0 to 49, 50 total iterations). - 最后一个输出的数字: The last time the loop runs,
iisnumOne - 1(49 in this case). Right after that,iincrements tonumOne, and the loop stops.
内容的提问来源于stack exchange,提问作者Carlos
相关产品推荐
相关产品推荐

