Hi.
I have a problem with integer and double usage in C++. I used the following 2 code lines to do the same mathematical operation but it returned different results. I can't understand the sourc of error in the first expression. Please help me to understand.
int a = 5;
int b = 10;
double c;
c = a/b; // gives the incorrect result: 0
even if I tried with
double c = 5/10; it gives incorrect result : 0
if I define it like this it gives correct result:
double a = 5;
int b = 10;
double c;
c = a/b; // gives the correct result: 0.5
If you divide two integers, an integer will be returned. This means that the decimal will be dropped. This is very useful for specific situations.
For example if you want to convert 1274 minutes into hours+minutes you would do this:
1 2
int hours = 1274/60; //This gives you the number of hours
int minutes = 1274%60; //This is the remainder that is left over representing the number of minutes
If integer division is not your intent, then ensure that you use floating point numbers (float or double) in your equation. This may be as simple as casting:
1 2 3
int a = 5;
int b = 10;
double c = ((double)a) / ((double) b)
This ensures that a and b are treated as doubles before being divided.
If you are using raw numbers, make sure to specify to the compiler that the number is a double or float like so:
1 2
double c = 5. / 10.; //The decimal specifies a double
double d = 5.f / 10.f; //The f specifies a float