循环难斐波拉切数列的改错方法有哪些?
- 内容介绍
- 文章标签
- 相关推荐
本文共计386个文字,预计阅读时间需要2分钟。
pythonclass Fibonacci: def __init__(self): self.previous=0.0 self.current=1.0
def next(self): self.previous, self.current=self.current, self.previous + self.current return int(self.previous)
def print_fibonacci_series(): fib=Fibonacci() for _ in range(20): print(fib.next(), end=' ')
print_fibonacci_series()
一、题目
输出Fabonacci数列的前20项 ,要求变量类型定义成浮点型,输出时只输出整数部分。以下程序只允许修改两行。
#include "stdio.h"
int main()
{
int i;
float f1=1,f2=1,f3;
for(i=1;i<=20;i++)
{
f3=f1+f2;
f2=f1;
f3=f2;
printf("%f",f1);
}
printf("\n");
return 0;
}
二、分析
1、初步分析
根据题意,只输出整数部分,则肯定要修改打印语句。
根据流程,先求f3,然后更新f1和f2,因此,第9行和第10行应该都有错误。
综上,则需要修改3行。但是题目只能修改2行,因此需要进一步分析。
2、确定错误语句
根据程序的功能分析,程序计算f3后,必须更新f1和f2,同时因为是更新后再打印,故需要打印的是f2-f1。即假设f1=2,f2=3;则f3=2+3=5。更新后f1=3,f2=5;,应该打印原来的f1即2。
所以第9行有错,在该行实现f2正确更新;第11行有错,在该行即要实现更新f1,还要实现正确的打印。
第10行其实为无效语句。
3、参考答案
第9行 f2=f3;
第11行 printf("%.0f ",f2-(f1=f2-f1));
本文共计386个文字,预计阅读时间需要2分钟。
pythonclass Fibonacci: def __init__(self): self.previous=0.0 self.current=1.0
def next(self): self.previous, self.current=self.current, self.previous + self.current return int(self.previous)
def print_fibonacci_series(): fib=Fibonacci() for _ in range(20): print(fib.next(), end=' ')
print_fibonacci_series()
一、题目
输出Fabonacci数列的前20项 ,要求变量类型定义成浮点型,输出时只输出整数部分。以下程序只允许修改两行。
#include "stdio.h"
int main()
{
int i;
float f1=1,f2=1,f3;
for(i=1;i<=20;i++)
{
f3=f1+f2;
f2=f1;
f3=f2;
printf("%f",f1);
}
printf("\n");
return 0;
}
二、分析
1、初步分析
根据题意,只输出整数部分,则肯定要修改打印语句。
根据流程,先求f3,然后更新f1和f2,因此,第9行和第10行应该都有错误。
综上,则需要修改3行。但是题目只能修改2行,因此需要进一步分析。
2、确定错误语句
根据程序的功能分析,程序计算f3后,必须更新f1和f2,同时因为是更新后再打印,故需要打印的是f2-f1。即假设f1=2,f2=3;则f3=2+3=5。更新后f1=3,f2=5;,应该打印原来的f1即2。
所以第9行有错,在该行实现f2正确更新;第11行有错,在该行即要实现更新f1,还要实现正确的打印。
第10行其实为无效语句。
3、参考答案
第9行 f2=f3;
第11行 printf("%.0f ",f2-(f1=f2-f1));

