簡體   English   中英

程序輸出(c ++的基本運算符)。 操作順序?

[英]Program output (Basic operators for c++). Order of operations?

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

似乎正在顯示的值是代碼行執行后的a值。 我確定這與操作順序有關,但是我不確定如何解決。 任何幫助是極大的贊賞。

在C ++中,未定義對運算符或函數的參數求值的順序。 如果對不同參數的求值有副作用,則只要編譯器認為合適,就會發生副作用,並且如果對同一對象進行多次修改,則結果將是不確定的行為。 如果要強制執行特定的求值順序,則需要將表達式分解為多個單獨的表達式,因為它們是按順序求值的,或者可以注入創建序列點的運算符。 但是,創建序列點的運算符不能很好地與鏈接輸出運算符配合使用。 強制在其他參數之前先求值第一個參數的運算符列表:

  • 運營商
  • 邏輯&&和|| 經營者
  • 條件運算符?:

當然,如果您重載了這些運算符中的任何一個,當它們成為常規函數調用時,它們將停止引入序列點。

您列出的所有運算符都是比較運算符,它們返回值true或false。

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

a- = b實際上是a = ab。

只要檢查您是否確定首先要這樣做?

順便說一句:if(a = b)也總是返回true,因為它總是成功,但是我認為我們不是故意這樣做的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM