21xrx.com
2024-05-20 11:28:32 Monday
登录
文章检索 我的文章 写文章
C++编程题目及答案
2023-07-12 03:05:14 深夜i     --     --
C++ 编程题目 答案 练习题 数据结构

C++是一种广泛应用于程序设计的计算机语言,已成为程序员们的必备技能之一。在学习C++的过程中,有许多编程题目需要我们完成。下面就为大家分享几道C++编程题目及其答案。

1. 题目:编写一个函数,将一个字符串中的所有字符按照出现次数的多少按照降序排列,并输出排序后的结果。

解答:


#include<iostream>

#include<algorithm>

using namespace std;

const int SIZE = 26; // 定义一个大小为26的常量

struct Node

  char ch;

  int count;

;

bool cmp(Node a, Node b)

  return a.count > b.count; // 按照出现次数从高到低排序

void sort_string(string str) {

  int count[SIZE] = { 0 };

  Node data[SIZE];

  int pos = 0;

  for (int i = 0; i < str.length(); i++) {

    if (isalpha(str[i])) {

      int index = tolower(str[i]) - 'a'; // 将大写字母转换为小写字母,然后计算出现次数

      count[index]++;

    }

  }

  for (char i = 'a'; i <= 'z'; i++) { // 将字符以及出现次数存入结构体数组中

    if (count[i - 'a']) {

      data[pos].ch = i;

      data[pos].count = count[i - 'a'];

      pos++;

    }

  }

  sort(data, data + pos, cmp); // 将结构体数组按出现次数降序排序

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

    cout << data[i].ch << ":" << data[i].count << endl; // 输出排序后的结果

  }

}

int main() {

  string str = "Hello, world!";

  sort_string(str);

  return 0;

}

2. 题目:编写一个函数,将一个字符串中的数字转换为整数,并输出该整数。

解答:


#include<iostream>

using namespace std;

int string_to_int(string str) {

  int result = 0;

  for (int i = 0; i < str.length(); i++) {

    if (isdigit(str[i])) { // 判断是否为数字

      result = result * 10 + (str[i] - '0'); // 将字符转换为数字

    }

  }

  return result;

}

int main() {

  string str = "12345";

  int result = string_to_int(str);

  cout << result << endl;

  return 0;

}

3. 题目:编写一个函数,以递归方式计算斐波那契数列中的第n项,并输出结果。

解答:


#include<iostream>

using namespace std;

int fibonacci(int n) {

  if (n <= 1)

    return 1;

  

  return fibonacci(n - 1) + fibonacci(n - 2); // 递归计算斐波那契数列

}

int main() {

  int n = 10;

  int result = fibonacci(n);

  cout << "第" << n << "项为:" << result << endl;

  return 0;

}

以上是一些C++编程题目及其解答,希望能够对大家的C++学习有所帮助。在学习C++的过程中,还需不断练习并查阅相关资料,才能更加深入地了解和掌握这门语言。

  
  

评论区

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