两个数字相加程序

C++Beginner
立即练习

介绍

在本实验中,你将学习如何使用 C++ 编程语言编写一个简单的程序来相加两个数字。你还将了解 C++ 中的变量声明、初始化、输入/输出操作以及基本的数学运算。

变量声明

首先,声明两个整数类型的变量 ab,用于存储用户输入。同时,声明一个变量 sum 并将其初始化为 0。

#include<iostream>

using namespace std;

int main()
{
    //变量声明
    int a, b;

    //变量声明并初始化
    int sum=0;

    //...
}

用户输入

使用 cincout 语句从用户获取输入。cout 用于向用户显示消息,cin 用于接收用户的输入。

cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << " =====  Program to add 2 numbers ===== \n\n";

cout << "Enter the first Number : ";
cin >> a;

cout << "\nEnter the second Number : ";
cin >> b;

两个数字相加

将两个数字 ab 相加,并将结果存储在变量 sum 中。

//将两个数字相加
sum = a + b;

显示结果

使用 cout 语句向用户显示结果。

//显示最终输出(sum)
cout << "\nAddition of the two numbers is : " << sum;

编译并运行程序

在终端中使用以下命令编译程序:

g++ ~/project/main.cpp -o main

在终端中使用以下命令运行程序:

./main

验证输出

运行程序后,你应该会在终端中看到以下输出:

Welcome to LabEx :-)


 =====  Program to add 2 numbers =====

Enter the first Number : 10

Enter the second Number : 20

Addition of the two numbers is : 30

总结

在本实验中,你学习了如何编写一个基本的 C++ 程序来相加两个数字。你还了解了 C++ 中的变量声明、初始化、用户输入/输出以及基本的数学运算。现在,你可以尝试其他数学运算或修改程序以满足你的需求。

以下是 main.cpp 文件的完整代码:

#include<iostream>

using namespace std;

int main()
{
    //变量声明
    int a, b;

    //变量声明并初始化
    int sum=0;

    //获取用户输入
    cout << "\n\nWelcome to LabEx :-)\n\n\n";
    cout << " =====  Program to add 2 numbers ===== \n\n";

    cout << "Enter the first Number : ";
    cin >> a;

    cout << "\nEnter the second Number : ";
    cin >> b;

    //将两个数字相加
    sum = a + b;

    //显示最终输出(sum)
    cout << "\nAddition of the two numbers is : " << sum;

    return 0;
}