using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{//数组 求 某一个 连续子数组的和 nums[5] { 5,3,4,6,7} index =
// 需要实际应用情况
//需要思考 :规定 index是下标 () [ ] ( ]的哪一种? 此代码约定 是其中的[]
//以及相等的情况
class Program
{
public int[] nums;
//构造函数中初始化
//类成员变量在构造函数中初始化是一种良好的实践,
//因为它将初始化逻辑封装在类的实例化过程中,使代码更具可维护性和清晰性。
public Program()
{
nums = new int[5] { 5, 3, 4, 6, 7 };
}
int Sum( int index1, int index2)
{
int i;//
//判断index1 index2是否合法
if (index1 < 0 || index1 >= nums.Length || index2 < 0 || index2 >= nums.Length)
{
Console.WriteLine(" 无效的索引");
return 0; //or throw an exception
}
//如果index1 =index2
if (index1 > index2) //如果index1> index2 交换一下
{
int temp = index2;
index2 = index1;
index1 = temp;
}
int sum = nums[index1];
//Console.WriteLine(sum+"我是for循环外的");
for (i = index1; i < index2; i++)
{
//Console.WriteLine(nums[i+1]);
sum += nums[i + 1];
//Console.WriteLine(sum + "我是for循环里的");
}
return sum;
}
static void Main(string[] args)
{
Program p = new Program();
//int nums = new int[5] { 5, 3, 4, 6, 7 };
p.nums = new int[5] { 5, 3, 4, 6, 7 };
int result = p.Sum(2,4);
Console.WriteLine(result);
Console.ReadKey();
}
}
}
//如果频繁调用同一个数组的,子数组 如何优化??