21xrx.com
2025-06-04 19:35:48 Wednesday
登录
文章检索 我的文章 写文章
「C++编程」简单代码集锦
2023-07-05 02:42:29 深夜i     16     0
C++语言 代码集锦 编程实例 简单代码 学习编程

C++编程是一门非常重要的编程语言,常用于开发软件、游戏等领域。作为一位初学者,掌握一些简单的代码是非常必要的,下面是一些代码集锦。

1. 输出语句

在C++中,使用cout语句可以输出文本或变量的值。例如:

#include <iostream>
using namespace std;
int main()
  cout << "Hello World!" << endl;
  int num = 5;
  cout << "The number is: " << num << endl;
  return 0;

输出结果为:

Hello World!
The number is: 5

2. 输入语句

使用cin语句可以从控制台输入数据并存储在变量中。例如:

#include <iostream>
using namespace std;
int main()
  int num;
  cout << "Enter a number: ";
  cin >> num;
  cout << "The number is: " << num << endl;
  return 0;

输出结果为:

Enter a number: 10
The number is: 10

3. 循环语句

使用for语句可以重复执行一段代码。例如:

#include <iostream>
using namespace std;
int main() {
  for(int i = 1; i <= 5; i++)
   cout << i << endl;
 
  return 0;
}

输出结果为:

1
2
3
4
5

4. 分支语句

使用if语句可以根据条件执行不同的代码块。例如:

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

输出结果为:

Enter a number: 7
The number is odd.

以上是一些C++简单代码集锦,初学者可以通过这些代码来熟悉语言的基本语法和使用方法,为日后的学习打下基础。

  
  

评论区