21xrx.com
2024-06-02 22:27:25 Sunday
登录
文章检索 我的文章 写文章
C++ 基础代码题及答案
2023-07-10 12:45:18 深夜i     --     --
C++ 基础代码题 答案 编程 数据结构

C++ 是一种广泛使用的编程语言,它的基础内容涵盖了许多重要的代码知识点和技巧。在本文中,我们将介绍几个 C++ 基础代码题及其答案,帮助初学者更好地掌握这门编程语言。

第一个题目是求一个整数数列的最大值和最小值。代码如下:


#include <iostream>

#include <algorithm>

using namespace std;

int main()

{

  int n;

  cin >> n;

  int a[n];

  for (int i = 0; i < n; i++)

  {

    cin >> a[i];

  }

  int max_value = *max_element(a, a + n);

  int min_value = *min_element(a, a + n);

  cout << "The max value is: " << max_value << endl;

  cout << "The min value is: " << min_value << endl;

  return 0;

}

第二个题目是判断一个数是否为素数。代码如下:


#include <iostream>

#include <cmath>

using namespace std;

bool is_prime(int n)

{

  if (n == 2) return true;

  if (n == 1 || n % 2 == 0) return false;

  int max_divisor = sqrt(n);

  for (int divisor = 3; divisor <= max_divisor; divisor += 2)

  {

    if (n % divisor == 0) return false;

  }

  return true;

}

int main()

{

  int n;

  cin >> n;

  bool result = is_prime(n);

  if (result)

  

    cout << n << " is a prime number." << endl;

  

  else

  

    cout << n << " is not a prime number." << endl;

  

  return 0;

}

第三个题目是求斐波那契数列的第 n 项,其中斐波那契数列是一个数列,第一个和第二个数为 1,后面每个数为前两个数之和。代码如下:


#include <iostream>

using namespace std;

int fibonacci(int n)

{

  if (n < 1) return 0;

  if (n == 1 || n == 2) return 1;

  int fibn_2 = 1;

  int fibn_1 = 1;

  for (int i = 3; i <= n; i++)

  {

    int fibn = fibn_1 + fibn_2;

    fibn_2 = fibn_1;

    fibn_1 = fibn;

  }

  return fibn_1;

}

int main()

{

  int n;

  cin >> n;

  int result = fibonacci(n);

  cout << "The " << n << "th number in the Fibonacci sequence is " << result << "." << endl;

  return 0;

}

以上就是三道 C++ 基础代码题及其答案,其中涉及到了数组、函数等基础知识点,可以帮助初学者更加深入地了解 C++ 编程语言。

  
  

评论区

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