C++

Simple C++ Maths

本篇我们将会介绍一些基础的C++操作,如减法,加法,除法和乘法。

我们将讨论下列操作

  • C++中的操作
  • 例子
  • 运算符的优先级
  • 例子

C++中的数学非常简单。请记住,C++数学运算遵循高中数学的运算法则。例如,乘法和除法的优先级高于加法和减法,可以用括号更改这些操作的求值顺序。

C++中的操作

C++中数学运算符操作如下:

SymbolsArithmetic operators
+add
subtract
/divide
*multiply
%modulus division
+=add and assign
-=subtract and assign
/=divide and assign
*=multiply and assign
%=mod and assign

例子

加,减,乘,除

让我们看看如何在C++中编写代码时使用这些操作

#include <iostream>
using namespace std;

int main() {
    int myInt = 100;

    myInt = myInt / 10; //myInt 现在为 10
    cout <<"Value of myInt after division by 10 is: " <<myInt << endl;
    myInt = myInt * 10; //myInt 又变为 100
    cout <<"Value of myInt after multiplication by 10 is: " <<myInt << endl;
    myInt = myInt + 50; //myInt 增加为 150
    cout <<"Value of myInt after addition of 50 is: " <<myInt << endl;
    myInt = myInt - 50; //myInt 变回一开始的 100
    cout <<"Value of myInt after subtraction of 50 is: " <<myInt << endl;

    myInt = myInt + 100 * 2; // myInt 现在是 300 
    cout << "Value of myInt after adding 100 and multiplying by 2 is: "<<myInt<<endl;
    myInt = (myInt + 100) * 2; // myInt 现在是 800 
    cout << "Value of myInt after doing the same operations using paranthesis is: "<<myInt<<endl;

    myInt -= 10; // myInt 现在 790 b
    cout << "Value of myInt after -=10 operation is: "<<myInt<<endl;
    myInt = myInt % 100; // myInt 现在是 90 
    cout << "Value of myInt after taking modulus with 100 is: "<<myInt<<endl;

    cout << "Value of myInt after all operations is: " <<myInt << endl;

    return 0; 
}

运算符的优先级

运算符的优先级指定表达式中包含多个运算符的运算顺序。操作符结合性指定在包含具有相同优先级的多个操作符的表达式中,一个操作数是与其左边的操作数结合还是与右边的操作数结合。下表显示了C++操作符的优先级和结合性(从高优先级到最低优先级)。

运算符描述结合性
从右到左
+    –加减操作
!    ~Logical NOT and bitwise NOT
*Indirection (dereference)
&Address-of
new, new[]Dynamic memory allocation
delete, delete[]Dynamic memory deallocation
=Direct assignment
+=    -=Assignment by sum and difference
*=    /=    %=Assignment by product, quotient, and remainder
<<=    >>=Assignment by bitwise left shift and right shift
&=    ^=    =Assignment by bitwise AND, XOR, and OR
++      —Suffix/postfix increment and decrement
从左到右
*    /    %Multiplication, division, and remainder
+    –Addition and subtraction
<<    >>Bitwise left shift and right shift
<    <=For relational operators
>    >=For relational operators
==     !=For relational operators
^Bitwise XOR (exclusive or)
&&Logical AND
||Logical OR
|Bitwise OR (inclusive or)
?:Ternary conditional

举例

如果你想计算给定的表达式:

20 + 30 * 2 / 10 – 3

根据C++操作符的优先级,他首先计算 30 * 2 = 60 然后计算 60 / 10 = 6, 因为乘法和除法的优先级相同,但是计算是先从左到右的,然后再加上 20 + 6 = 26 ,减去 26 - 3 = 23,同样,加法与减法的优先级相同,但是从左到右进行运算,所以最终答案 23.

#include <iostream>
using namespace std;

int main() {
  // 20 + 30 * 2 / 10 - 3
  cout << "Answer is " <<  20 + 30 * 2 / 10 - 3 << endl;
  return 0;
}

你可以试一试这个程序,并尝试写出自己的程序!

发表评论