21xrx.com
2025-03-28 14:15:39 Friday
文章检索 我的文章 写文章
C++简单编程代码
2023-06-25 06:50:02 深夜i     25     0
C++ 编程 代码 简单 基础

C++是一种面向对象的编程语言,它结合了C语言的高效性和面向对象编程的特点,可以用于编写各种类型的程序。下面是一些简单的C++编程代码,帮助初学者快速入门。

1. 输出"Hello, world!"

在C++中,使用cout语句可以将文本输出到屏幕上。

#include <iostream>
using namespace std;
int main()
  cout << "Hello

2. 计算两个整数的和

可以使用cin语句获取用户输入的两个整数,并使用+运算符计算它们的和。

#include <iostream>
using namespace std;
int main() {
  int a, b, sum;
  cout << "Enter two integers: ";
  cin >> a >> b;
  sum = a + b;
  cout << "The sum is: " << sum << endl;
  return 0;
}

3. 判断一个数是否为偶数

使用模运算符(%)可以判断一个数是否为偶数。

#include <iostream>
using namespace std;
int main() {
  int num;
  cout << "Enter an integer: ";
  cin >> num;
  if (num % 2 == 0)
    cout << num << " is an even number." << endl;
   else
    cout << num << " is an odd number." << endl;
  
  return 0;
}

4. 输出九九乘法表

使用两个for循环嵌套可以输出九九乘法表。

#include <iostream>
using namespace std;
int main() {
  for (int i = 1; i <= 9; i++) {
    for (int j = 1; j <= i; j++) {
      cout << i << "*" << j << "=" << i * j << "\t";
    }
    cout << endl;
  }
  return 0;
}

5. 冒泡排序

冒泡排序是一种简单的排序算法,可以按照从小到大的顺序排列一个整数数组。

#include <iostream>
using namespace std;
void bubble_sort(int arr[], int n) {
  for (int i = 0; i < n - 1; i++) {
    for (int j = 0; j < n - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        int temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }
}
int main() {
  int arr[] = 12;
  int n = sizeof(arr) / sizeof(arr[0]);
  bubble_sort(arr, n);
  cout << "Sorted array: ";
  for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;
  return 0;
}

这些代码只是C++编程的冰山一角,但它们展示了C++的基本语法和常见应用场景。对于初学者来说,学习这些代码是一个不错的开始,可以为以后深入学习奠定坚实的基础。

  
  

评论区

请求出错了