ComputerProgramming3.The Nuts and Bolts of C++OperatorsAnexpression oftencomprises oneofmoreoperators.The assignment operator '-'assigns a value to a variable orconstant,e.g.x = 39;Several mathematical operators are provided by C++Let a be 3, b be 4 and x is declared as an integer,OperatorsMeaningExamplesAdd//7b;x+X一aSubtract-11/b;xOX?大Multiply12//b;X大X1Divide//b;0(why?)X一X%modulus3//b;一(why?)美X二?3modulo4is3
3. The Nuts and Bolts of C++ Computer Programming Operators • An expression often comprises one of more operators. • The assignment operator '=' assigns a value to a variable or constant, e.g. x = 39; • Several mathematical operators are provided by C++. • Let a be 3, b be 4 and x is declared as an integer, Operators Meaning + Add - Subtract * Multiply / Divide % modulus Examples x = a + b; // x = 7 x = a - b; // x = -1 x = a * b; // x = 12 x = a / b; // x = 0 (why?) x = a % b; // x = 3 (why?) 3 modulo 4 is 3
ComputerProgramming3. The Nuts and Bolts of C++IntegerandFloating PointDivisionsx,yofmain() arenotx,yofintDiv(int, int)#include<iostream>using namespace std;Castingvoid intDiv(int x, int y)1int z = x/y;Askthecompilertotemporarilycout << "z: " << z << endl;considerx as a floatingpoint1no.,i.e.5.0 in this casevoid floatDiv(int x, int y)1float a = (float)x;// old stylefloat b = static cast<float>(y);// ANSI stylefloat c = a/b;c"e:Visual Studio Projectscout << "c: " << c << endl;2:1+c:1.66667Only give integerint main()division result,i.e. 11intx=5,y=3;intDiv(x,y);floatDiv(x,y);Give floating pointreturn O;division result. i.e. 1.66
3. The Nuts and Bolts of C++ Computer Programming Integer and Floating Point Divisions #include <iostream> using namespace std; void intDiv(int x, int y) { int z = x/y; cout << "z: " << z << endl; } void floatDiv(int x, int y) { float a = (float)x; // old style float b = static_cast<float>(y); // ANSI style float c = a/b; cout << "c: " << c << endl; } int main() { int x = 5, y = 3; intDiv(x,y); floatDiv(x,y); return 0; } Only give integer division result, i.e. 1 Give floating point division result, i.e. 1.66. Casting Ask the compiler to temporarily consider x as a floating point no., i.e. 5.0 in this case. x, y of main() are not x, y of intDiv(int, int)