21xrx.com
2024-06-03 07:07:06 Monday
登录
文章检索 我的文章 写文章
C++编程题目及答案
2023-07-04 04:20:09 深夜i     --     --
C++ programming Exercise problems Answers and solutions Object-oriented programming Data structures

作为一位C++程序员,不断练习编程是必不可少的。编程题目既是检验自己技能的途径,也是提升技能的好方法。下面介绍几个C++编程题目及答案,希望对C++程序员有所帮助。

1. 闰年判断问题

题目:输入一个年份,判断该年份是否为闰年。

答案:


#include<iostream>

using namespace std;

int main() {

  int year;

  cin >> year;

  if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)

    cout << year << "是闰年" << endl;

   else

    cout << year << "不是闰年" << endl;

  

  return 0;

}

2. 数组最大值问题

题目:输入一个长度不超过100的整型数组,输出该数组中的最大值。

答案:


#include<iostream>

#include<algorithm>

using namespace std;

int main() {

  int a[100];

  int n;

  cin >> n;

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

    cin >> a[i];

  }

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

  cout << "数组中的最大值为:" << max_number << endl;

  return 0;

}

3. 字符串反转问题

题目:输入一个字符串,将其反转后输出。

答案:


#include<iostream>

#include<string.h>

using namespace std;

int main() {

  char str[100];

  cin >> str;

  int len = strlen(str);

  for (int i = 0; i < len / 2; i++) {

    swap(str[i], str[len - i - 1]);

  }

  cout << str << endl;

  return 0;

}

4. 斐波那契数列问题

题目:输入一个正整数n,输出斐波那契数列的第n项。斐波那契数列的第一项和第二项为1,从第三项开始,每一项都是前两项的和。

答案:


#include<iostream>

using namespace std;

int fibonacci(int n) {

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

    return 1;

   else {

    return fibonacci(n - 1) + fibonacci(n - 2);

  }

}

int main() {

  int n;

  cin >> n;

  int f = fibonacci(n);

  cout << "斐波那契数列的第" << n << "项为:" << f << endl;

  return 0;

}

以上就是四个C++编程题目及答案。希望这些编程题目能够帮助C++程序员提升编程技能,更好地应对编程挑战。

  
  

评论区

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