21xrx.com
2025-03-23 14:30:53 Sunday
文章检索 我的文章 写文章
C++代码汇总
2023-06-23 17:15:32 深夜i     13     0
C++ 代码 汇总 编程 计算机语言

C++是一种计算机编程语言,它是一种高级编程语言,用于开发系统软件和应用软件。C++在计算机科学领域中是非常重要的,因为它提供了一种可以与计算机硬件交互的高效方法。以下是一些C++代码示例的汇总:

1. Hello World程序

#include <iostream>
using namespace std;
int main()
  cout << "Hello World!" << endl;
  return 0;

2. 变量声明和赋值

#include <iostream>
using namespace std;
int main() {
  // 声明变量
  int x;
  int y;
  int z;
  
  // 赋值
  x = 1;
  y = 2;
  z = x + y;
  
  // 输出结果
  cout << "x = " << x << endl;
  cout << "y = " << y << endl;
  cout << "z = " << z << endl;
  return 0;
}

3. 条件语句

#include <iostream>
using namespace std;
int main() {
  // 声明变量
  int x = 10;
  // 条件语句
  if (x > 5)
    cout << "x is greater than 5" << endl;
   else
    cout << "x is less than or equal to 5" << endl;
  
  return 0;
}

4. 循环语句

#include <iostream>
using namespace std;
int main() {
  // 声明变量
  int x = 0;
  
  // 循环语句
  while (x < 10) {
    cout << x << endl;
    x++;
  }
  return 0;
}

5. 数组

#include <iostream>
using namespace std;
int main() {
  // 声明并初始化数组
  int arr[5] = 1;
  
  // 循环遍历数组并输出元素
  for (int i = 0; i < 5; i++) {
    cout << "arr[" << i << "] = " << arr[i] << endl;
  }
  return 0;
}

6. 函数

#include <iostream>
using namespace std;
// 定义函数
int add(int x, int y) {
  return x + y;
}
int main() {
  // 调用函数
  int result = add(1, 2);
  cout << "1 + 2 = " << result << endl;
  return 0;
}

总之,C++是一种功能强大的编程语言,它支持多种编程范式,如面向过程、面向对象、泛型编程等。通过使用C++,开发人员可以轻松地创建高效且可靠的软件应用程序。以上代码示例是初学者入门后必备的基础知识,我们需要不断练习才能够熟练掌握它们。

  
  

评论区