【发布时间】:2014-03-02 13:29:08
【问题描述】:
我有一个名为 sample.txt 的文件,其中包含 1000 个整数(正数和负数)。首先,我将文件复制到一个大小为 1000 的数组中(比如 a)。 我的目标是在 a 中找到最大的 子数组 并找到其中元素的总和。 如果数组的连续元素按递增顺序排列,则数组是子数组。例如在数组 {12,23,3,1,-56,2,4,6,45,49,1,2,-10} 中,子数组是 {-56,2 ,4,6,45,49}。 然后我需要计算这个子数组的元素之和。
下面是我尝试使用 C 程序解决问题的方法。 我是非CS专业的,本学期刚完成C编程。非常感谢您的帮助。
int sum(int a[],int i,int temp)
{
int sum=0,j;
for(j=i;j<i+temp;j++)
sum+=a[j];
printf("Sum = %d", sum);
return 0;
}
int main()
{
FILE *f1;
int a[1000],b[900];
int number,i=-1,counter=0,temp=1,check=1,j;
f1 = fopen("sample.txt","r");
while (!feof (f1) && fscanf (f1, "%d", &number) && i++ < 1000 )// copying the file to an array
a[i] = number;
fclose(f1);
for(i=1;i<1000;i++)
{
if(a[i-1]<a[i])
counter++;
else
{
if(counter>temp)
temp=counter;
counter=0;
}
}
temp++;
printf("Temp= %d", temp); // the length of the largest sub array whose elements are in increasing order
sum(a,i,temp);
return 0;
}
【问题讨论】:
-
你遇到了什么问题
-
我的程序输出不正确。看来我的逻辑是错误的什么的。