21xrx.com
2024-06-03 05:32:48 Monday
登录
文章检索 我的文章 写文章
C++ 代码分享
2023-07-05 17:41:07 深夜i     --     --
C++ 代码分享 编程技巧 开源 程序设计

C++ 是一种广泛使用的编程语言,用来创建各种各样的应用程序和软件。在 C++ 中,你可以使用很多不同的编程技巧和代码来实现各种功能。本文将分享一些有趣的 C++ 代码,供大家参考和学习。

1. 打印一个菱形

这是一个简单的 C++ 程序,用于打印一个菱形。您可以在控制台中执行此代码,以看到漂亮的输出效果。


#include <iostream>

using namespace std;

int main()

{

  int n = 5;

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

    for (int j = 1; j <= n - i; j++)

      cout << " ";

    for (int j = 1; j <= 2 * i - 1; j++)

      cout << "*";

    cout << endl;

  }

  for (int i = n - 1; i >= 1; i--) {

    for (int j = 1; j <= n - i; j++)

      cout << " ";

    for (int j = 1; j <= 2 * i - 1; j++)

      cout << "*";

    cout << endl;

  }

  return 0;

}

2. 将字符串反转

这个程序使用了一个简单的算法,将输入的字符串反转。通过修改输入字符串的顺序,可以将字符串反转。


#include <iostream>

#include <cstring>

using namespace std;

void reverseStr(char str[], int len)

{

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

    char temp = str[i];

    str[i] = str[len - i - 1];

    str[len - i - 1] = temp;

  }

}

int main()

{

  char str[] = "Hello, world!";

  int len = strlen(str);

  reverseStr(str, len);

  cout << str;

  return 0;

}

3. 计算斐波那契数列

斐波那契数列是一个经典的数学问题,可以使用递归或循环算法来计算。这个例子展示了如何使用循环算法计算斐波那契数列。


#include <iostream>

using namespace std;

int fibonacci(int n)

{

  int previous = 0, current = 1;

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

    int temp = previous + current;

    previous = current;

    current = temp;

  }

  return previous;

}

int main()

{

  cout << fibonacci(10);

  return 0;

}

4. 字符串分割成单词

这个程序使用 strtok() 函数,将输入的字符串分割成单词。我们可以通过指定分隔符来定义单词的分割方式。


#include <iostream>

#include <cstring>

using namespace std;

int main()

{

  char str[] = "Hello, world! This is a test.";

  char* token = strtok(str, " ,.!");

  while (token != NULL) {

    cout << token << endl;

    token = strtok(NULL, " ,.!");

  }

  return 0;

}

5. 矩阵乘法

这个示例演示了如何使用数组和嵌套循环执行矩阵乘法。这可以是用于编写图形和游戏的重要算法。


#include <iostream>

using namespace std;

#define rows 3

#define cols 3

void matmul(int a[][cols], int b[][cols], int res[][cols])

{

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

    for (int j = 0; j < cols; j++) {

      res[i][j] = 0;

      for (int k = 0; k < cols; k++)

        res[i][j] += a[i][k] * b[k][j];

    }

  }

}

void printmat(int mat[][cols])

{

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

    for (int j = 0; j < cols; j++)

      cout << mat[i][j] << " ";

    cout << endl;

  }

}

int main()

{

  int a[rows][cols] = { {1, 2, 3},

             {4, 5, 6},

             {7, 8, 9} };

  int b[rows][cols] = { {9, 8, 7},

             {6, 5, 4},

             {3, 2, 1} };

  int res[rows][cols];

  matmul(a, b, res);

  printmat(res);

  return 0;

}

总之,这些代码只是 C++ 的冰山一角,C++ 还有很多有趣的代码,可以探索和学习。希望这些例子能对想要学习或提高 C++ 技能的人们有所帮助。

  
  

评论区

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