计算斐波那契数列的第 n 个数,其中 n 在命令行中输入
我想编写一个程序来计算斐波那契序列的第 n 个数字,这是我使用 printf 和 scanf 完成的。但我希望更改我的程序,以便在命令行中输入序列号,而不是在程序提示时输入。这就是我想出的。它可以编译,但是当我运行它时它崩溃了......不知道为什么。任何建议将不胜感激。
这是一个使用迭代计算斐波那契代码第 n 个数的程序。我是这样写的: 您必须在命令行 argv[1] 中输入要计算的序列号。然后程序使用这个命令行 参数并在 while 循环中使用它,并打印该数字。
#include <stdio.h>
int main( int argc, char**argv ) {
int fib[3] = {0,1};
int counter = 0;
printf("The %dth Fibonacci number is:\n", atoi(argv[1]));
while ( counter < atoi(argv[1]) ) {
fib[2] = fib[0] + fib[1];
fib[0] = fib[1];
fib[1] = fib[2];
counter++;
}
printf("%d\n", fib[0]);
getchar();
return 0;
}
I want to write a program to compute the nth number of the fibonnacci sequence, which i had done using printf and scanf. But I was hoping to change my program so that the sequence number is entered at the command line rather than entered when prompted by the program. This is what i've come up with. It compiles, but then it crashes when i run it... not sure why. Any suggestions would be appreciated.
This is a program to compute the nth number of the fibonnacci code using iteration. I have written it as such:
You must enter the number of the sequence you wish to compute at the command line argv[1]. The program then takes this command line
argument and uses it in the while loop, and also prints this number.
#include <stdio.h>
int main( int argc, char**argv ) {
int fib[3] = {0,1};
int counter = 0;
printf("The %dth Fibonacci number is:\n", atoi(argv[1]));
while ( counter < atoi(argv[1]) ) {
fib[2] = fib[0] + fib[1];
fib[0] = fib[1];
fib[1] = fib[2];
counter++;
}
printf("%d\n", fib[0]);
getchar();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
检查用户是否确实传递了参数:
如果没有传递,则 argv[1] 为 null,并且您将崩溃
Check if the user actually passed an argument:
If he didn't,
argv[1]
is null, and you'll crash程序应该检查是否存在命令行参数:
如果没有提供参数,它可能会崩溃。
= = = = = 编辑 = = = = =
一旦修复了上述错误,我就看不到任何导致崩溃的原因。这工作正常:
The program should check if a command line argument is present:
If no argument is supplied, it will probably crash.
= = = = = edit = = = = =
I don't see any cause for a crash once the bug above is fixed. This works okay:
你用什么号码测试的?因为 int 无法保存高于第 50 个斐波那契数的任何数字。我必须在我的算法类中执行类似的操作,我们必须找到第 239 个斐波那契数,即
64202014863723094126901777428873111802307548623680
这是 int 和 long 都不能正确保存的东西。我认为这不会使它崩溃,但如果您需要找到一个大的斐波那契数,请注意。
What number did you test it with? Because an int won't be able to hold anything higher than the ~50th Fibonacci number. I had to do something like this in my Algorithms class and we had to find the 239th Fibonacci number which was
64202014863723094126901777428873111802307548623680
Which is something an int nor a long can hold correctly.I don't think that would make it crash but just giving a heads up if you need to find a large Fibonacci number.
如果您想打印系列直至指定为命令行参数的特定数量,请使用以下程序:
If you want to print the series upto a certain number specified as command line argument, then go for this program: