Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division in C++ not working as expected

Tags:

c++

division

People also ask

How does division work in C?

In the C Programming Language, the div function divides numerator by denominator. Based on that division calculation, the div function returns a structure containing two members - quotient and remainder.

Does division round up or down in C?

Yes, the result is always truncated towards zero. It will round towards the smallest absolute value.

What happens if you divide by zero in C?

The default one does nothing, so if division by zero is detected, the division function returns zero.

How do you do proper division in C++?

The division operator / computes the quotient (either between float or integer variables). The modulus operator % computes the remainder when one integer is divided by another (modulus operator cannot be used for floating-type variables).


You are missing the fact that 3 and 5 are integers, so you are getting integer division. To make the compiler perform floating point division, make one of them a real number:

 double f = 3.0 / 5;

It doesn't need to be .0, you can also do 3./5 or 3/5. or 3e+0 / 5 or 3 / 5e-0 or 0xCp-2 / 5 or... There only needs to be an indicator involved so that the compiler knows it's supposed to perform the division as floating point.

Another possibility: double f=double(3)/5. That's much more typing, but it leaves no doubt to what you are doing.

Or simply use double f=.6, that also does the trick...


try this:

double f = 3.0/5.0;

this should fix your problem


Try putting a .0 after one of the divisors. This will convert them into floating point literals.


You are using integers. You can many things to make your constants double like leftaroundabout states, however that is not good clean good. It is hard to read and confusing. If you want 3 and 5 make them 3.0 and 5.0. Everyone will know what you mean if they are forced to read your code. Much of what he/she states really requires you to know C/C++ and how floats are storage to make heads or tails.


In case, you save your generic variables with int and would like to obtain the ratio as double:

using namespace std;
int main()
{
   int x = 7;
   int y = 4;
   double ratio;
   ratio = static_cast<double>(x)/static_cast<double>(y);
   cout << "ratio =\t"<<ratio<< endl;
}