计算数列的和

C++C++Beginner
立即练习

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

介绍

在本实验中,我们将学习如何编写一个 C++ 程序来计算数列 1 + 2 + 4 + 8 + 16 + 32 + ... + n 的和。我们将使用两种不同的方法。第一种方法使用 for 循环来累加序列中的值,而第二种方法使用数学公式来计算和。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/StandardLibraryGroup(["`Standard Library`"]) cpp/ControlFlowGroup -.-> cpp/for_loop("`For Loop`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/user_input("`User Input`") cpp/IOandFileHandlingGroup -.-> cpp/files("`Files`") cpp/StandardLibraryGroup -.-> cpp/math("`Math`") subgraph Lab Skills cpp/for_loop -.-> lab-96197{{"`计算数列的和`"}} cpp/output -.-> lab-96197{{"`计算数列的和`"}} cpp/user_input -.-> lab-96197{{"`计算数列的和`"}} cpp/files -.-> lab-96197{{"`计算数列的和`"}} cpp/math -.-> lab-96197{{"`计算数列的和`"}} end

创建一个新文件

首先,打开终端并导航到 ~/project 目录。在该目录下,创建一个名为 main.cpp 的新文件。我们可以使用以下命令来完成:

touch ~/project/main.cpp

接下来,在你喜欢的文本编辑器中打开该文件。

使用 for 循环

在这种方法中,我们使用 for 循环遍历序列并将从 1 到 n 的数字相加。我们将把和存储在一个名为 sum 的变量中。

将以下代码添加到你的 main.cpp 文件中:

#include <iostream>

int main() {
    int n, sum = 0;
    std::cout << "Enter the value of n: ";
    std::cin >> n;

    for(int i = 1; i <= n; ++i) {
        sum += i;
    }

    std::cout << "The sum of the sequence is: " << sum << std::endl;

    return 0;
}

在这里,我们使用 std::cout 函数显示一条消息,要求用户输入 n 的值。然后,我们使用 std::cin 函数读取用户输入的 n 值。在开始 for 循环之前,我们将 sum 初始化为 0

for 循环从 1n 遍历 i 的值,并将每个值加到 sum 中。最后,我们使用 std::cout 显示和。

在运行程序之前,我们需要编译它。在终端中,导航到 ~/project 目录并运行以下命令:

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

这将编译并运行程序。你应该会看到一条消息,要求你输入 n 的值。输入值后,程序将显示序列的和。

使用数学公式

在这种方法中,我们使用数学公式来计算序列的和。公式为 sum = 2^n - 1,其中 n 是序列中的项数。

将以下代码添加到你的 main.cpp 文件中:

#include <iostream>
#include <cmath>

int main() {
    int n;
    std::cout << "Enter the value of n: ";
    std::cin >> n;

    int sum = pow(2, n) - 1;

    std::cout << "The sum of the sequence is: " << sum << std::endl;

    return 0;
}

在这里,我们使用 std::pow 函数计算 2^n。然后从这个值中减去 1 以得到序列的和。最后,我们使用 std::cout 显示和。

在运行程序之前,我们需要编译它。在终端中,导航到 ~/project 目录并运行以下命令:

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

这将编译并运行程序。你应该会看到一条消息,要求你输入 n 的值。输入值后,程序将显示序列的和。

完整代码

以下是 main.cpp 的完整代码:

#include <iostream>
#include <cmath>

int main() {
    int n;
    std::cout << "Enter the value of n: ";
    std::cin >> n;

    int sum = pow(2, n) - 1;

    std::cout << "The sum of the sequence is: " << sum << std::endl;

    return 0;
}

#include <iostream>

int main() {
    int n, sum = 0;
    std::cout << "Enter the value of n: ";
    std::cin >> n;

    for(int i = 1; i <= n; ++i) {
        sum += i;
    }

    std::cout << "The sum of the sequence is: " << sum << std::endl;

    return 0;
}

总结

在本实验中,我们学习了如何编写一个 C++ 程序来计算数列 1 + 2 + 4 + 8 + 16 + 32 + ... + n 的和。我们使用了两种不同的方法——一种使用 for 循环,另一种使用数学公式。你可以使用其中任何一种方法来计算任何算术序列的和。

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