You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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}");

为什么这样改?

  • 循环执行次数: i starts at 0, increments by 1 after each loop run, and stops when i is no longer less than numOne. That means it runs exactly numOne times (0 to 49, 50 total iterations).
  • 最后一个输出的数字: The last time the loop runs, i is numOne - 1 (49 in this case). Right after that, i increments to numOne, and the loop stops.

内容的提问来源于stack exchange,提问作者Carlos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:42:51