怎呢转成函数写
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main( )
{
int n;
cin>>n;
int a[24+1]={0,1,1};
for(int i=3;i<=n;i++){
a[i]=a[i-1]+a[i-2];
}
cout<<a[n];
return 0;
}
怎呢转成函数写
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main( )
{
int n;
cin>>n;
int a[24+1]={0,1,1};
for(int i=3;i<=n;i++){
a[i]=a[i-1]+a[i-2];
}
cout<<a[n];
return 0;
}
引自免费微信小程序:皆我百晓生
将给定的代码转换为一个独立的函数是一个很好的实践,这可以提高代码的可读性和重用性。下面是将上述代码转换为一个单独的函数的示例,该函数计算斐波那契数列的第n项。
#include<iostream>
#include<bits/stdc++..h> // Note: This header is not recommended. Use specific headers instead.
using namespace std;
// Function to calculate the nth Fibonacci number
long long fibonacci(int n) {
if (n <= 1) return n; // Base cases
long long fib[24+1] = {0, 1, 1}; // Initialize array with base cases
for(int i = 3; i <= n; i++) {
fib[i] = fib[i-1] + fib[i-2]; // Calculate current Fibonacci number
}
return fib[n]; // Return the nth Fibonacci number
}
int main() {
int n;
cin >> n; // Read input from user
// Call the function and print the result
cout << fibonacci(n);
return 0;
}
为了改进代码质量,建议使用更具体的头文件而不是bits/stdc++.h
,因为它包含了所有标准库,这可能不是最佳做法。以下是使用具体头文件的版本:
#include <iostream>
#include <vector>
using namespace std;
// Function to calculate the nth Fibonacci number
long long fibonacci(int n) {
if (n <= 1) return n; // Base cases
vector<long long> fib(n+1); // Use vector instead of array for dynamic size
fib[0] = 0;
fib[1] = 1;
for(int i = 2; i <= n; i++) {
fib[i] = fib[i-1] + fib[i-2]; // Calculate current Fibonacci number
}
return fib[n]; // Return the nth Fibonacci number
}
int main() {
int n;
cin >> n; // Read input from user
// Call the function and print the result
cout << fibonacci(n);
return 0;
}
在这个版本中,我们使用了vector
容器,它提供了动态大小数组的功能,这比固定大小的数组更灵活。同时,我们也去掉了bits/stdc++.h
,并替换了<vector>
和<iostream>
两个具体的头文件。