0
// H2.cpp : Tihs program runs different mathmatical operations on numbers given by the user

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int a;
    cout << "Enter a number for a: "; //Prompts the user for a and b inputs
    cin >> a;

    int b;
    cout << "Enter a number for b: ";
    cin >> b;

    cout << "A is " << a << "\tB is " << b << endl;
    cout <<"Sum of a and b is equal to " << a << " + " << b << " and the result is " << (a + b) << endl; //Performs addition operator and gives output
    cout <<"Product of a and b is equal to " << a << " * " << b << " and the result is " << (a * b) << endl;
    cout <<"a > b is " << a << " > " << b << " and the result is " << (a > b) << endl;
    cout <<"a < b is " << a << " > " << b << " and the result is " << (a < b) << endl;
    cout <<"a == b is " << a << " == " << b << " and the result is " << (a == b) << endl; //Performs boolean operator and outputs result
    cout <<"a >= b is " << a << " >= " << b << " and the result is " << (a >= b) << endl;
    cout <<"a <= b is " << a << " <= " << b << " and the result is " << (a <= b) << endl;
    cout <<"a != b is " << a << " != " << b << " and the result is " << (a != b) << endl;
    cout <<"a -= b is " << a << " -= " << b << " and the result is a = " << (a -= b) << endl; //Performs - operator on a - b and makes a equal to the new result
    cout <<"a /= b is " << a << " /= " << b << " and the result is a = " << (a /= b) << endl;
    cout <<"a %= b is " << a << " %= " << b << " and the result is a = " << (a %= b) << endl; //Performs % operator on a % b and makes a equal to the new result. Ripple effect created from previous 2 lines as the value of a changes each time.

return 0;

The output I'm concerned with is here:

a -= b is -4198672 -= 4198672 and the result is a = -4198672
a /= b is -1 /= 4198672 and the result is a = -1
a %= b is -1 %= 4198672 and the result is a = -1

It seems like the value for a being displayed is the value of a after the line of code is executed. I'm sure that has something to do with the order of operations, but I'm not sure how to get around that. Any help is greatly appreciated.

4

2 回答 2

1

C++ 中未定义运算符或函数的参数计算顺序。如果对不同参数的评估有副作用,则只要编译器认为合适,并且如果对同一对象进行多次修改,结果就会出现未定义的行为。如果要强制执行特定的评估顺序,则需要将表达式分解为多个单独的表达式,因为它们是按顺序评估的,或者您可以注入创建序列点的运算符。但是,创建序列点的运算符不能很好地与链接输出运算符一起使用。强制在其他参数之前评估第一个参数的运算符列表是:

  • 运营商
  • 逻辑 && 和 || 运营商
  • 条件运算符?:

当然,如果您重载这些运算符中的任何一个,它们将停止引入序列点,因为它们成为正常的函数调用。

于 2013-09-20T00:48:16.810 回答
0

您列出的所有运算符都是返回值 true 或 false 的比较运算符。

除了:-=、/= 和 %= 运算符

a-=b 实际上是 a=ab。

只需检查您是否确定您首先想要这个?

顺便说一句: if(a=b) 也返回 true,因为它总是成功,但我不认为我们是故意这样做的。

于 2013-09-20T00:47:20.200 回答