程序输出(c ++的基本运算符)。运营顺序?

时间:2013-09-20 00:25:39

标签: c++ operator-keyword

// 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;

我关注的输出是:

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

似乎显示的值是执行代码行之后的值。我确定这与操作顺序有关,但我不确定如何解决这个问题。非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

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

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

当然,如果你重载这些操作符中的任何一个,它们就会在它们成为正常的函数调用时停止引入一个序列点。

答案 1 :(得分:0)

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

除外: - =,/ =和%=运算符

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

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

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