c - 在斐波那契数列中使用 switch 语句

标签 c

我正在编写一个程序,使用递归计算给定整数的斐波那契数。我创建了自己的函数“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/

相关文章:

c - 串口通信问题(C代码)

c - 为什么这个字符串反转程序不起作用?

c++ - 从被调用者的角度来看,如何检测内存是动态的还是静态的?

c - 在不使用 getpass (3) 的情况下在 C 中获取密码?

c - 展开链表数组与节点

c++ - 如何更改我的 C++ 代码以使其可在 C 中使用?

c - 信号处理程序中的格式化 I/O

c - 函数 strtok() 有什么问题?

sql - 解析 .sql 文件时输出错误

c - 为什么在下面的代码上出现段错误?