我正在运行此程序
#include <stdio.h>
int main ()
{
int n;
int a = 1;
int b = 2;
int product;
int i;
printf("How many numbers of the sequence would you like \n");
scanf("%d",&n);
for (i=0;i<n;i++)
{
printf("%d\n",a);
product = a * b;
a = b;
b = product;
}
return 0;
}
当我输入n = 3时,结果是1 2 2
为什么 ?我的意思是让它显示1 2 4,我做错了什么?为什么打印1 2 2。
答案 0 :(得分:2)
为什么要打印1 2 2。
printf("%d\n",a);
处的逐步跟踪:
i a b product
0 1 2 ?
1 2 2 2
2 2 4 4
3 4 8 8
4 8 32 32
答案 1 :(得分:0)
1 2 2
因为您在每次迭代中打印a
而不是product
并且a
的值为 -
1st iteration a=1
2nd iteration a=2 // a=b and b=2 i.e a=2
3rd iteration a=2 // why ? because again a=b and b did not change
thus output 1 2 2
简单的解决方案是 -
1.初始化product
至1
// int product =1;
2.print product
代替printf("%d\n",a);
// printf("%d\n",product);