重载运算符 减号
Given two numbers, and the task is to find their addition using the minus (-) operator.
给定两个数字,任务是使用减(-)运算符查找它们的加法 。
As we have discusses in C/C++ arithmetic operators that plus (+) operator adds the numbers and minus (-) operator subtracts the numbers. But adding two numbers using minus (-) operator can also be done – It's a simple mathematical trick.
正如我们在C / C ++算术运算符中讨论的那样,加号( + )运算符将数字相加,而负号( - )运算符将数字相减。 但是,也可以使用减号( - )运算符将两个数字相加–这是一个简单的数学技巧。
As we know that, minus and minus becomes plus. Thus, to add two numbers – we can subtract the negative of the second number from the first number.
众所周知,负号和负号变为正号。 因此,要添加两个数字–我们可以从第一个数字中减去第二个数字的负数 。
first_number - (-second_number)
Example:
例:
Input:
x = 10
y = 20
Operation:
result = x - (-y)
Output:
result = 30
Program:
程序:
#include <iostream>
using namespace std;
int main()
{
int x = 10;
int y = 20;
// printing the numbers
cout << "x : " << x << endl;
cout << "y : " << y << endl;
// calculation
int result = x - (-y);
// printing the result
cout << "result : " << result << endl;
cout << endl;
// assigning the other values
x = -10;
y = 20;
// printing the numbers
cout << "x : " << x << endl;
cout << "y : " << y << endl;
// calculation
result = x - (-y);
// printing the result
cout << "result : " << result << endl;
cout << endl;
// assigning the other values
x = -10;
y = -20;
// printing the numbers
cout << "x : " << x << endl;
cout << "y : " << y << endl;
// calculation
result = x - (-y);
// printing the result
cout << "result : " << result << endl;
return 0;
}
Output:
输出:
x : 10
y : 20
result : 30
x : -10
y : 20
result : 10
x : -10
y : -20
result : -30
翻译自: https://www.includehelp.com/cpp-programs/adding-of-two-numbers-using-minus-operator-in-c-cpp.aspx
重载运算符 减号