我有一个任务是添加和减去两个int变量而不使用内置运算符(+和 - ),而是使用递增和递减运算符。我该怎么做呢?
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;
感谢您的帮助!
答案 0 :(得分:4)
使用for
循环。
e.g。
for (; add1; add1--, add2++);
假设add1为正, add2
将为add1 + add2
相似的减法想法
答案 1 :(得分:2)
很明显,您需要使用循环或递归函数。例如
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;
答案 2 :(得分:0)
除非您需要编写令牌解析器并创建自己的解释器和编译器,否则必须使用某种内置运算符来执行此操作。但我猜是因为这个问题非常基础,所以不要求你这样做。
你可以这样做:
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;
编辑 - 如果/ 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;