does not work when an odd number is entered in the number of terms
#include<stdio.h>
//fibonacci series with details...
int main (){
int n,ter;
int x1=1,x2,x3,x4;
printf("Enter the number of terms:");
scanf("%d",&ter);
for(n=0;n<=--ter;n++){
x1+=x2;
x2+=x1;
x3=x1+x2;
printf("%d+%d=%d\n",x1,x2,x3);
x4=x2+x3;
printf("%d+%d=%d\n",x2,x3,x4);
}
printf("\nThx for trying :)");
return 0;
}
[当我为学期号写3时,它写了4学期。我该如何解决?
for(n=0;n<=--ter;n++){
这看起来非常可疑。你们都在增加当前学期数和在降低终止点这一事实通常意味着您接近结束条件的速度是您应有的两倍。
想想当您想要第八项时会发生什么:n
从零开始,ter
从八开始,这些是循环:
n ter loop#
0 8 1
1 7 2
2 6 3
3 5 4
4 4 5
根据我的计算,这甚至与请求的八次迭代还差得远。
现在,此不是偶数计数问题的原因是您进行计算的方式:
x1 += x2;
x2 += x1;
x3 = x1 + x2;
这实际上使x1
和x2
前进了[[Two个步,而不是一个步,所以迭代次数的一半就可以了。换句话说,它将去:
1, 1
2, 3
5, 8
13, 21 ...
而不是:
1, 1 1, 2 2, 3 3, 5 5, 8 ...
但是,这仅对个术语有效,因为偶数除以2,很好,是均匀的:-)如果您有一个even
odd
数字,则实际遍历值似乎比所需的多一倍,因为即使只需要一个,最终迭代仍将执行两个步骤。更常见的方法(不受奇数影响的方法是一次执行one
步骤,例如使用:int x1 = 0, x2 = 1, x3 = 1; // or "1, 1, 2" depending on what
// you consider first term.
for (int n = 1; n < ter; n++) {
printf ("%d + %d = %d\n", x1, x2, x3);
x1 = x2; // simply "shift" the values left ONE spot.
x2 = x3;
x3 = x1 + x2;
}
printf ("%d + %d = %d\n", x1, x2, x3);
另外,另一个问题是在使用x2
之前,您实际上并没有对其进行初始化。这可能很好,但是这纯粹是偶然的,不是您应该依靠的东西。