C语言分支结构斐波那契数列
时间: 2023-11-20 18:52:43 浏览: 85
C语言分支结构斐波那契数列可以使用if-else语句或者switch语句来实现。以下是两种实现方法:
1. if-else语句实现斐波那契数列
```
#include <stdio.h>
int main() {
int n, i, t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 1; i <= n; ++i) {
if (i == 1) {
printf("%d, ", t1);
continue;
}
if (i == 2) {
printf("%d, ", t2);
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
printf("%d, ", nextTerm);
}
return 0;
}
```
2. switch语句实现斐波那契数列
```
#include <stdio.h>
int main() {
int n, i, t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 1; i <= n; ++i) {
switch (i) {
case 1:
printf("%d, ", t1);
break;
case 2:
printf("%d, ", t2);
break;
default:
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
printf("%d, ", nextTerm);
}
}
return 0;
}
```
阅读全文