计算倒数级数的和

C++C++Beginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,我们将学习如何编写一个 C++ 程序来计算一个级数的和。我们将处理的级数是自然数倒数平方的和。简单来说,程序将计算 1 + 1/2^2 + 1/3^3 + 1/4^4 + ... + 1/N^N 的和。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/FunctionsGroup(["`Functions`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/StandardLibraryGroup(["`Standard Library`"]) cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") cpp/ControlFlowGroup -.-> cpp/for_loop("`For Loop`") cpp/FunctionsGroup -.-> cpp/function_parameters("`Function Parameters`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/user_input("`User Input`") cpp/IOandFileHandlingGroup -.-> cpp/files("`Files`") cpp/StandardLibraryGroup -.-> cpp/math("`Math`") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("`Code Formatting`") subgraph Lab Skills cpp/variables -.-> lab-96193{{"`计算倒数级数的和`"}} cpp/data_types -.-> lab-96193{{"`计算倒数级数的和`"}} cpp/for_loop -.-> lab-96193{{"`计算倒数级数的和`"}} cpp/function_parameters -.-> lab-96193{{"`计算倒数级数的和`"}} cpp/output -.-> lab-96193{{"`计算倒数级数的和`"}} cpp/user_input -.-> lab-96193{{"`计算倒数级数的和`"}} cpp/files -.-> lab-96193{{"`计算倒数级数的和`"}} cpp/math -.-> lab-96193{{"`计算倒数级数的和`"}} cpp/code_formatting -.-> lab-96193{{"`计算倒数级数的和`"}} end

在项目目录中创建一个新文件

在你的项目目录中创建一个名为 main.cpp 的新文件。

touch ~/project/main.cpp

添加必要的头文件

在程序中添加必要的头文件。在本程序中,我们需要 iostreamcmath 头文件。

#include<iostream>
#include<cmath>
using namespace std;

编写 findsum() 函数

在这一步中,我们将定义 findsum() 函数,用于计算级数的和。该函数接收 N 的值作为输入,并返回级数的和。

double findsum(int N) {
    double sum = 0;
    for(int i=1; i<=N; i++) {
        sum += pow((double)1/i,i);
    }
    return sum;
}

在上述代码中,我们使用了 <cmath> 头文件中的 pow() 函数来计算每一项的幂。我们还使用了 double 数据类型来获取精确的值。

编写 main() 函数

在这一步中,我们将编写 main() 函数,该函数将以整数 N 的形式从用户那里获取输入。然后,我们将调用 findsum() 函数来计算级数的和。最后,我们将打印结果。

int main() {
    int N;
    cout << "Enter the value of N: ";
    cin >> N;
    double sum = findsum(N);
    cout << "Sum of the series is: " << sum << endl;
    return 0;
}

编译并运行程序

保存对 main.cpp 文件的更改,并在终端中运行以下命令:

g++ main.cpp -o main && ./main

成功编译并运行后,程序将提示用户输入 N 的值。输入 N 的值后,程序将返回级数的和。

main.cpp 文件的完整代码:

#include <iostream>
#include <cmath>

using namespace std;

double findsum(int N) {
    double sum = 0;
    for(int i=1; i<=N; i++) {
        sum += pow((double)1/i,i);
    }
    return sum;
}

int main() {
    int N;
    cout << "Enter the value of N: ";
    cin >> N;
    double sum = findsum(N);
    cout << "Sum of the series is: " << sum << endl;
    return 0;
}

总结

在本实验中,我们学习了如何编写一个 C++ 程序来计算级数的和。我们使用循环遍历所有项,并将它们相加以得到级数的和。我们还使用了 pow() 函数来计算每一项的幂。

您可能感兴趣的其他 C++ 教程