我正在编写一个程序,使用递归计算给定整数的斐波那契数。我创建了自己的函数“fibonacci”,并使程序在循环中运行,正如您在代码中看到的那样。
程序要我使用switch语句来操作菜单(菜单是用户有两个选择的菜单,要么选择查找斐波那契,要么退出程序),我被困在如何使用switch语句上以便使用菜单。
这是我到目前为止编写的代码
#include <stdio.h>
int fibonacci(int num);
int main(int argc, char const *argv[]) {
int choice;
int num;
int sequence;
printf("1) Calculate Fibonacci\n");
printf("2) Exit\n");
scanf("%d", &choice);
if (choice == 1)
{
do
{
printf("Input integer n :\n");
scanf("%d", &num);
if (num < 0)
{
printf("n should be a positive integer (n >= 1). Retry\n");
}
} while (num < 0);
}
if (choice == 1 && num > 0)
{
printf("Fibonacci sequence of %d terms\n", num);
最佳答案
摘自 Kernighan 和 Ritchie 的《C 编程语言》:
"The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values, and branches accordingly."
所以它看起来应该类似于:
while ((choice = getchar())!= EOF){
switch (choice){
case '1':
// calculate Fibonacci sequence
break;
case '2':
return 0;
}
}
正如评论之一所建议的,要么在开始时初始化局部变量,要么检查 getchar() 或 scanf() 调用的返回值,因为未初始化变量的值是不确定的。
如果你刚刚开始学习C,我建议你阅读我提到的那本书。它相对较短,并且有很多有用的示例。
关于c - 在斐波那契数列中使用 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42494932/