21xrx.com
2024-09-17 04:27:50 Tuesday
登录
文章检索 我的文章 写文章
五个有趣的C++代码程序
2023-07-05 09:04:23 深夜i     --     --
随机数生成器 random srand rand 排序算法 quick sort bubble sort merge sort 前缀树(字

C ++是一种高效的编程语言,已被广泛应用于许多领域,例如游戏开发,桌面应用程序,Web应用程序和移动应用程序。在C ++语言中,创建有趣的代码程序是很有趣的事情,以下是五个有趣的C ++代码程序。

1. Hello World!

C ++中最经典的程序是Hello World。虽然这个程序非常简单,但它是入门级程序员必须了解的。

 c++

#include<iostream>

using namespace std;

int main()

World!";

  return 0;

2. 猜数字游戏

这个程序让用户猜一个数字,直到猜中为止。 该程序使用了随机生成的数字和while循环,以使猜测成为有趣的游戏。

 c++

#include<iostream>

#include<cstdlib>

#include<ctime>

using namespace std;

int main()

{

  srand((unsigned)time(0));

  int num = rand() % 100;

  int guess = -1;

  while (guess != num)

  {

    cout << "Guess a number between 1 and 100: ";

    cin >> guess;

    if (guess > num)

      cout << "Too high\n";

    else if (guess < num)

      cout << "Too low\n";

    else

      cout << "Correct!\n";

  }

  return 0;

}

3. 矩阵运算

这个程序创建了一个矩阵类,定义了矩阵相加的运算符。 这使程序员可以轻松地处理矩阵运算。

 c++

#include<iostream>

using namespace std;

class Matrix

{

public:

  int m[3][3];

  Matrix operator+(Matrix a)

  {

    Matrix t;

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

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

        t.m[i][j] = m[i][j] + a.m[i][j];

    return t;

  }

};

int main()

{

  Matrix A = {

    2,

    4,

    8

  };

  Matrix B = {

    9,

    5,

    2

  };

  Matrix C = A + B;

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

  {

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

      cout << C.m[i][j] << " ";

    cout << endl;

  }

  return 0;

}

4. 斐波那契数列

这个程序打印出n个斐波那契数列的数字。 斐波那契数列是指每个数字等于其前两个数字之和的数列。

 c++

#include<iostream>

using namespace std;

void fibonacci(int n)

{

  int a = 0, b = 1, c;

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

  {

    cout << a << " ";

    c = a + b;

    a = b;

    b = c;

  }

}

int main()

{

  int n;

  cout << "Enter a number: ";

  cin >> n;

  fibonacci(n);

  return 0;

}

5. 逆波兰表达式

这个程序计算逆波兰表达式,它是一种后缀表达式,其中运算符出现在操作数之后。 逆波兰表达式非常有用,因为它们容易通过堆栈计算。

 c++

#include<iostream>

#include<stack>

using namespace std;

int evaluate(string exp)

{

  stack<int> s;

  for (int i = 0; i < exp.size(); ++i)

  {

    if (isdigit(exp[i]))

      s.push(exp[i] - '0');

    else

    {

      int a = s.top();

      s.pop();

      int b = s.top();

      s.pop();

      switch (exp[i])

      {

      case '+': s.push(a + b); break;

      case '-': s.push(b - a); break;

      case '*': s.push(a * b); break;

      case '/': s.push(b / a); break;

      }

    }

  }

  return s.top();

}

int main()

{

  string exp = "25 3 + 6 2 * -";

  cout << evaluate(exp);

  return 0;

}

无论您是刚入门的C ++编程人员还是经验丰富的C ++编程人员,上述代码段都可以帮助您编写出富有创意的代码。 这只是C ++提供的许多有趣代码的冰山一角,让您深入挖掘吧。

  
  

评论区

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