在课堂上,助教解释说 A[end+1] 比 A[end] 好,但我忘记了原因。有人可以帮助解释是否有必要,因为没有它该程序似乎可以正常工作。另外,如果您愿意帮助我为函数中的 ERROR 触发器返回 -1。在发生错误时,我没有为最终总和打印 -1 值,我具体添加了什么以及在哪里打印错误消息而不是 -1?
/* Progrm.c
Author:
Adds fibonacci terms from start to end inclusive.
*/
#include <stdlib.h>
#include <stdio.h>
int f(int start, int end);
int main() {
int start, end, response;
do {
printf("Enter start\n");
scanf("%d",&start);
printf("\nEnter end\n");
scanf("%d",&end);
printf("\n%d\n",f(start,end));
printf("\nWould you like to solve additional problems ? \n"
"Please enter 1 for yes or 0 for no: ");
scanf("%d", &response);
} while ( response == 1 );
system("pause");
return 0;
}
int f(int start, int end) {
if(start<=0||end<=0||start>end) {
fprintf( stderr, "\nError - Input data is invalid. Please enter "
"start: > 0, end: > 0, \nand start < end.\n");
return -1;
}
int A[end+1],i; /*Can you replace A[end+1] with just A[end]*/
A[1]=1; /*and not encounter problems?*/
A[2]=1;
for(i=3;i<=end;i++)
A[i]=A[i-1]+A[i-2];
int sum=0;
for(i=start;i<=end;i++)
sum+=A[i];
return sum;
}