C++ 程序:两数相加

编写一个C++程序,通过多个示例来对两个数字进行相加。下面的代码使用算术加法运算符对num1和num2进行相加。

#include<iostream>

using namespace std;

int main()
{
    int num1 = 10, num2 = 20, sum;
    
    sum = num1 + num2;
    cout << "Sum of Two Numbers " << num1 <<" and " << num2 << " = " << sum;
    
    return 0;
}
Sum of Two Numbers 10 and 20 = 30

下面的代码允许用户输入两个整数值,然后将它们相加。

#include<iostream>

using namespace std;

int main()
{
	int num1, num2, sum;
	
	cout << "Please enter the First Number  : ";
	cin >> num1;
	
	cout << "Please enter the Second Number : ";
	cin >> num2;
	
	sum = num1 + num2;
	cout << "Sum of Two Numbers " << num1 <<" and " << num2 << " = " << sum;
	
	return 0;
}
Please enter the First Number  : 5
Please enter the Second Number : 220
Sum of Two Numbers 5 and 220 = 225

使用函数相加两数程序

在这里,我们创建了一个接受两个参数并返回这两个参数之和的函数。接下来,我们在C++ main()程序中调用该函数。

// using functions
#include<iostream>

using namespace std;
int add(int x, int y)
{
	return x + y;
}

int main()
{
	int num1, num2, sum;
	
	cout << "Please enter the First Number  : ";
	cin >> num1;
	
	cout << "Please enter the Second Number : ";
	cin >> num2;
	
	sum = add(num1, num2);
	cout << "Sum of Two Numbers " << num1 <<" and " << num2 << " = " << sum;
	
	return 0;
}
C++ Program to Add Two Numbers

在这个使用OOPS的两数相加示例中,我们使用一个带有公共方法的独立类来执行加法。

#include<iostream>

using namespace std;
class Addition {
	
	public: int add(int x, int y){
		return x + y;
	}
};
int main()
{
	int num1, num2, sum;
	
	cout << "Please enter the First Number  : ";
	cin >> num1;
	
	cout << "Please enter the Second Number : ";
	cin >> num2;
	
	Addition ad;
	
	sum = ad.add(num1, num2);
	cout << "Sum of Two Numbers " << num1 <<" and " << num2 << " = " << sum;
	
	return 0;
}
Please enter the First Number  : 99
Please enter the Second Number : 145
Sum of Two Numbers 99 and 145 = 244