Zff121017 2024-06-14 20:38 采纳率: 25%
浏览 3

怎呢转成函数写C++

怎呢转成函数写


#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;
}
  • 写回答

6条回答 默认 最新

  • 专家-赤兔[在线] 全栈领域优质创作者 2024-06-14 20:38
    关注

    引自免费微信小程序:皆我百晓生

    将给定的代码转换为一个独立的函数是一个很好的实践,这可以提高代码的可读性和重用性。下面是将上述代码转换为一个单独的函数的示例,该函数计算斐波那契数列的第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>两个具体的头文件。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 6月14日

悬赏问题

  • ¥15 模电中二极管,三极管和电容的应用
  • ¥15 关于模型导入UNITY的.FBX: Check external application preferences.警告。
  • ¥15 气象网格数据与卫星轨道数据如何匹配
  • ¥100 java ee ssm项目 悬赏,感兴趣直接联系我
  • ¥15 微软账户问题不小心注销了好像
  • ¥15 x264库中预测模式字IPM、运动向量差MVD、量化后的DCT系数的位置
  • ¥15 curl 命令调用正常,程序调用报 java.net.ConnectException: connection refused
  • ¥20 关于web前端如何播放二次加密m3u8视频的问题
  • ¥15 使用百度地图api 位置函数报错?
  • ¥15 metamask如何添加TRON自定义网络