21xrx.com
2025-04-06 20:50:56 Sunday
文章检索 我的文章 写文章
易懂的C++编程示例
2023-06-22 21:32:17 深夜i     15     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 a, b;
  cin >> a >> b;
  cout << a + b << endl;
  return 0;
}

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

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

4. 输出几个斐波那契数列。

#include <iostream>
using namespace std;
int main()
{
  int n, a = 0, b = 1, c;
  cin >> n;
  cout << a << " " << b << " ";
  for(int i = 0; i < n - 2; i++){
    c = a + b;
    cout << c << " ";
    a = b;
    b = c;
  }
  cout << endl;
  return 0;
}

5. 实现冒泡排序。

#include <iostream>
using namespace std;
int main()
{
  int a[10] = 0;
  int temp;
  for(int i = 0; i < 9; i++){
    for(int j = 0; j < 9 - i; j++){
      if(a[j] > a[j+1]){
        temp = a[j+1];
        a[j+1] = a[j];
        a[j] = temp;
      }
    }
  }
  for(int i = 0; i < 10; i++)
    cout << a[i] << " ";
  cout << endl;
  return 0;
}

以上就是我们所介绍的五个易懂的C++编程示例,适合初学者进行练习。希望这些代码能够对你的编程学习有所帮助。

  
  

评论区

请求出错了