简体   繁体   English

使用增量和减量运算符进行加法和减法。 C ++

[英]Addition and subtraction using increment and decrement operators. C++

I have been given a task to add and subtract two int variables WITHOUT using the built in operators (+ and -) and instead using the increment and decrement operators. 我被赋予一项添加和减去两个int变量的任务,而无需使用内置运算符(+和-),而是使用递增和递减运算符。 How do I go about doing this? 我该怎么做呢?

    int add1;
    int add2; 
    int total;

    cout << "Please enter the 2 numbers you wish to add" << endl;
    cin >> add1;
    cin >> add2;

    //perform addition using increment operators

    return 0;

thanks for the help! 谢谢您的帮助!

Use a for loop. 使用for循环。

eg 例如

 for (; add1; add1--, add2++);

add2 will be add1 + add2 assuming add1 is positive 假设add1为正,则add2将为add1 + add2

Similar idea for subtraction 减法的类似想法

It is obvious that you need to use either loops or recursive functions. 显然,您需要使用循环或递归函数。 For example 例如

int add1;
int add2;
cout << "Please enter the 2 numbers you wish to add" << endl;
cin >> add1;
cin >> add2;

int sum = add1; 
for ( int i = 0; i < add2; i++ ) ++sum;

int diff = add1; 
for ( int i = 0; i < add2; i++ ) --diff;

std::cout << "sum is equal to: " << sum << std::endl;  
std::cout << "difference is equal to: " << diff << std::endl;  

return 0;

You have to use some sort of built in operators to perform this unless you are required to write a token parser and create your own interpreter and compiler. 除非需要编写令牌解析器并创建自己的解释器和编译器,否则必须使用某种内置的运算符来执行此操作。 But I'm guessing since the question is quite basic, it's not asking you to do that. 但是我猜想,因为这个问题是非常基本的,不是在要求您这样做。

You can simply do this: 您可以简单地做到这一点:

int add1;
int add2;
cout << "Please enter the 2 numbers you wish to add" << endl;
cin >> add1;
cin >> add2;

//perform addition using increment operator
cout << (add1 += add2);

return 0;

EDIT - added decrement operator with less than or equal to 0 if/else: 编辑-如果小于/等于,则添加小于或等于0的减量运算符:

int add1;
int add2;
int sub1;
int sub2;

cout << "Please enter the 2 numbers you wish to add" << endl;
cin >> add1;
cin >> add2;

//perform addition using increment operator
cout << (add1 += add2);

cout << "Please enter the 2 numbers you wish to subtract" << endl;
cin >> sub1;
cin >> sub2;

if((sub1 - sub2) <= 0)
{
    cout << "Number is less than or equal to 0." << endl;
}
else
    cout << (sub1 -= sub2);


return 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM