Thursday, July 30, 2009

Integer division c++?

i need the operator used for this and a simple exsample





ps:i am not talking about mod %

Integer division c++?
In C++ the "/" operator can be used for floating point division or for real division! it depends on what type of variable you use.


To perform an integer division: simply use "/" with two int variables or, if your variables are floating point, simply cast to integer with the operator "(int)".





Similarly you can force a floating point division by using the cast to float operator "(float)".





Example:


=======


#include %26lt;iostream%26gt;


using namespace std;








void main()


{


float float1=3.333;


float float2=1.5;





int int1=26;


int int2=5;





//output the reversed text


cout %26lt;%26lt; "Floating point division" %26lt;%26lt; endl;


cout %26lt;%26lt; float1 %26lt;%26lt; " / " %26lt;%26lt; float2 %26lt;%26lt; " = " %26lt;%26lt; float1/float2 %26lt;%26lt; endl;


cout %26lt;%26lt; int1 %26lt;%26lt; " / " %26lt;%26lt; int2 %26lt;%26lt; " = " %26lt;%26lt; (float)int1/int2 %26lt;%26lt; endl;





cout %26lt;%26lt; endl %26lt;%26lt; "Integer division" %26lt;%26lt; endl;


cout %26lt;%26lt; float1 %26lt;%26lt; " / " %26lt;%26lt; float2 %26lt;%26lt; " = " %26lt;%26lt; (int)float1/float2 %26lt;%26lt; endl;


cout %26lt;%26lt; int1 %26lt;%26lt; " / " %26lt;%26lt; int2 %26lt;%26lt; " = " %26lt;%26lt; int1/int2 %26lt;%26lt; endl;





}





Output:


=====


Floating point division


3.333 / 1.5 = 2.222


26 / 5 = 5.2





Integer division


3.333 / 1.5 = 2


26 / 5 = 5
Reply:DIV (like MOD) is not a keyword in C++ (but it is indeed used in other languages to perform integer divisions) Report It

Reply:Do a normal division and truncate.





Rawlyn.


No comments:

Post a Comment