这是一个带有迭代Fibonacci的C程序,使用clock()来计算获得第n个Fibonacci数所需的时间.程序循环不停.我知道方程是正确的,因为我能够在没有时钟功能的情况下正确运行程序.任何帮助表示赞赏!
#include<time.h>
#include<sys/file.h>
#include<stdio.h>
int main ( )
{
int j=1, fib, n, i=1, k=0;
int choice;
float x,y,z;
x = clock(); //start clock
printf("input the fib number you want: ");
scanf("$d", &n);
while (k <=n)
{
fib = i + j;
i = j;
j = fib;
++k;
printf( "The fib number is %d\n ", fib);
}
y =clock(); // end clock
z = (y - x) / CLOCKS_PER_SEC;
printf("\n\nThe execution time was: %.15f", z);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
scanf("$d", &n);需要scanf("%d", &n);.机会是,n当你的程序启动时获得随机值会使你的循环条件失败.
如评论中@dasblinkenlight所述,如果您想要有用的测量,则应在用户输入后开始计时.
此外,尽管大多数书籍似乎都没有涵盖它,但检查返回值scanf()是一个好主意,因为它可以像上面那样捕获拼写错误(感谢@WilliamPursell).像下面这样的东西会起作用:
if( scanf( "whatever random and incorrect format string", &n ) != 1 ) {
/* exit with error message */
}
Run Code Online (Sandbox Code Playgroud)
成功时,该函数返回成功填充的参数列表的项数.由于匹配失败,读取错误或文件结束的范围,此计数可以匹配预期的项目数或更少(甚至为零).
如果在读取时发生读取错误或达到文件结尾,则设置正确的指示符(feof或ferror).并且,如果在可以成功读取任何数据之前发生任何一个,
EOF则返回.如果解释宽字符时发生编码错误,则函数将errno设置为
EILSEQ.
| 归档时间: |
|
| 查看次数: |
165 次 |
| 最近记录: |