21xrx.com
2024-06-03 05:38:27 Monday
登录
文章检索 我的文章 写文章
C++编程:输出1!~10!
2023-06-22 15:13:12 深夜i     --     --
C++ 编程 阶乘 输出 1-10

C++是一门强大的编程语言,是许多程序员的首选。在C++中,可以轻松编写出许多不同的程序,包括数学计算、字符串处理、图像处理等。

本篇文章将介绍如何使用C++编程输出1!~10!的阶乘。阶乘是数学中的一种运算,表示将一个整数连乘到1的乘积。例如5!即5*4*3*2*1=120。

首先,我们需要定义一个函数来计算阶乘,可以用C++中的循环结构来实现。代码如下:


int factorial(int n){

  int result = 1;

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

    result *= i;

  }

  return result;

}

上述代码中,我们定义了一个函数factorial,该函数有一个整数参数n,返回的是n的阶乘。函数中使用了for循环来进行n的连乘,最后将结果存入变量result中,并返回该变量的值。

接下来,我们可以编写主函数来输出1!~10!的结果。代码如下:


#include<iostream>

using namespace std;

int factorial(int n);

int main(){

  for(int i = 1; i <= 10; i++){

    cout << i << "! = " << factorial(i) << endl;

  }

  return 0;

}

int factorial(int n){

  int result = 1;

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

    result *= i;

  }

  return result;

}

在主函数中,我们使用了for循环来依次计算1~10的阶乘,并输出结果。其中,使用了cout语句来输出结果,endl语句来进行换行。

运行上述代码,我们将得到如下输出:


1! = 1

2! = 2

3! = 6

4! = 24

5! = 120

6! = 720

7! = 5040

8! = 40320

9! = 362880

10! = 3628800

以上便是使用C++编程输出1!~10!的阶乘的过程。代码简单易懂,适合初学者进行学习和实践。学习C++编程,将拓宽我们的思维和视野,为我们的职业发展带来无限可能。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复