c# 等差数列公差2,从1到99求和控制台代M码
时间: 2024-09-26 22:02:08 浏览: 67
在C#中,你可以使用for循环和累加的方式来计算等差数列从1到99,公差为2的和。以下是相应的控制台应用程序代码:
```csharp
using System;
class Program
{
static void Main(string[] args)
{
int start = 1;
int difference = 2;
int sum = 0;
int number = start; // 当前数字
while (number <= 99) // 当当前数字小于等于99时继续循环
{
sum += number; // 将当前数字加到总和上
number += difference; // 更新当前数字(每次增加2)
}
Console.WriteLine($"等差数列(公差2)从1到99的和为: {sum}");
}
}
```
这个程序会先初始化起始值(1)、公差(2),然后通过while循环逐次累加到`sum`变量中,并更新`number`,直到超过99为止。最后,它会在控制台上打印出等差数列的总和。
阅读全文
相关推荐









