21xrx.com
2024-06-03 07:02:56 Monday
登录
文章检索 我的文章 写文章
C++示例代码实现
2023-07-05 13:54:48 深夜i     --     --
C++ 代码 示例 实现 编程

C++是一种高级编程语言,不仅拥有强大的功能,而且易于学习和使用。许多软件开发人员都喜欢使用C++编写代码,并且这种语言被广泛应用于各种应用程序和系统的开发中。

以下是一些基于C++的示例代码,可以帮助初学者更好地了解这种编程语言:

1. Hello World程序

这是一个经典的C++程序,实现了简单的输出功能。

#include

using namespace std;

int main()

  cout << "Hello World!" << endl;

  return 0;

2. 简单计算器

这个程序实现了简单的加减乘除功能,并且能够处理无效的输入。

#include

using namespace std;

int main()

{

  double num1, num2;

  char op;

  cout << "Enter the first number: ";

  cin >> num1;

  cout << "Enter an operator (+, -, *, /): ";

  cin >> op;

  cout << "Enter the second number: ";

  cin >> num2;

  if (op == '+')

    cout << num1 << " + " << num2 << " = " << num1 + num2 << endl;

  else if (op == '-')

    cout << num1 << " - " << num2 << " = " << num1 - num2 << endl;

  else if (op == '*')

    cout << num1 << " * " << num2 << " = " << num1 * num2 << endl;

  else if (op == '/')

  {

    if (num2 == 0)

      cout << "Error! Division by zero." << endl;

    else

      cout << num1 << " / " << num2 << " = " << num1 / num2 << endl;

  }

  else

    cout << "Invalid operator." << endl;

  return 0;

}

3. 数组排序

这个程序演示了如何使用冒泡排序算法对数组进行排序。

#include

using namespace std;

int main()

{

  int arr[6] = 3;

  int i, j, temp;

  for (i = 0; i < 6; i++)

  {

    for (j = 0; j < 6 - i - 1; j++)

    {

      if (arr[j] > arr[j + 1])

      {

        temp = arr[j];

        arr[j] = arr[j + 1];

        arr[j + 1] = temp;

      }

    }

  }

  cout << "Sorted array in ascending order: ";

  for (i = 0; i < 6; i++)

    cout << arr[i] << " ";

  cout << endl;

  return 0;

}

这些示例代码展示了C++中的一些基本语法和功能。对于初学者来说,重要的是多练习和实践,以加深对这种编程语言的理解。

  
  

评论区

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