21xrx.com
2025-03-28 00:42:22 Friday
文章检索 我的文章 写文章
C++编程入门:简单编程例子
2023-06-25 03:32:09 深夜i     7     0
C++ 编程入门 简单例子

C++是一种强大的编程语言,它广泛用于软件开发和计算机编程。作为编程初学者,学习C++编程是一项基础必须掌握的技能。在本文中,我们将给出三个简单的C++编程例子,以帮助您入门。

例子1:输出“Hello World”

‘Hello World’是作为计算机编程入门的标准输出语句之一,让我们通过C++编程完成它。

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

这段代码的输出是:

Hello World

例子2:计算两个数字的总和

在C++编程中,我们可以编写代码来计算两个数字的总和。让我们通过一个示例程序来实现它。

#include <iostream>
using namespace std;
int main() {
  int num1, num2;
  int sum;
  cout << "Enter the first number: ";
  cin >> num1;
  cout << "Enter the second number: ";
  cin >> num2;
  sum = num1 + num2;
  cout << "The sum is " << sum << endl;
  return 0;
}

这段代码要求用户输入两个数字,它们的和将被计算并显示在屏幕上。在程序运行时,您将看到以下输出:

Enter the first number: 2
Enter the second number: 3
The sum is 5

例子3:计算圆的面积

让我们用C++编程实现计算圆的面积的程序。圆的面积可以通过以下公式计算:

Area = π * radius * radius

为了计算圆的面积,我们需要输入半径值并应用上述公式,如下所示:

#include <iostream>
using namespace std;
int main() {
  float radius, area;
  cout << "Enter the radius of circle: ";
  cin >> radius;
  area = 3.14159 * radius * radius;
  cout << "Area of circle is: " << area << endl;
  return 0;
}

这段代码要求用户输入圆的半径值,并计算并输出圆的面积。在程序运行时,您将看到以下输出:

Enter the radius of circle: 2.5
Area of circle is: 19.6349

以上是三个简单的C++编程例子,它们可以帮助您入门C++编程。通过这些示例,您将了解如何使用C++编程语言创建基本程序,包括输出语句、变量和算术操作符。始终记住,在学习C++编程时,实践是最好的方法!

  
  
下一篇: C++输入单词

评论区

请求出错了