Decimal places question

Hello every body,

I have a problem with outputing the correct decimal places by using the division operator. Eg)
-----------------------
#include <iostream>
using namespace std;
int main()
{
float a;
a = 2534/100;

cout << a;
return 0;
}
The above will output a final value of 25 for "a" despite the data type is float. Now if I write another program:
-----------------------------
#include <iostream>
using namespace std;
int main()
{
float a = 2534, b;
b = a/100;
cout << b;
return 0;
}
This will output a final value of 25.34, which is the correct decimal places I want.

So, my question is, why does c++ output two different values when both of the programs above are pretty much the same.

Thank you.

integer divisions returns an integer, that sometimes is useful.
you may use a literal double 2534./100
oooh, I think I understand this now. So, when I assign the variable "a" with a whole number like 2534, this will automatically change the data type "float" into the data type "int"? And if I wanna maintain the result as a float or double, I must change the number into a real number?

Another question is, the other code that made up is exactly the same as the first one, but I simply assigned another variable (b) to be inserted to cout....but the result has decimal places even though I used int division.

Last edited on
No, a variable does not change its type.
In your second case you do not have integer division because `a' is not an integer but a float.

2534 is an integer, 100 is an integer, 2534/100 is an integer
ahh i see. ok I got it.

Thank you very much for the electrification :)
Topic archived. No new replies allowed.