Not registered yet?
Register now! It is easy and done in 1 minute and gives you access to special discounts and much more!
I was working on something else, but everything came out as zero, so I made this minimalistic example, and the output is still 0.
int main(int argc, char** argv)
std::cout << f;
What am I missing?
In case, you save your generic variables with int and would like to obtain the ratio as double:
using namespace std;
int x = 7;
int y = 4;
ratio = static_cast<double>(x)/static_cast<double>(y);
cout << "ratio =\t"<<ratio<< endl;
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.
Well, I thought it was obvious that 0xCp-2 / 5 was not to be taken really serious! ...But as for using 3.0: that's a matter of taste. I personally hate to write it this way, because in science, any finite number of digits after the decimal point hints some kind of inaccuracy in measured values etc., so when I see 3.0 I always think of 3±.05, and 3.0/5.0 is .6±.01 to me. That's not double precision! I prefer 3./5.
0xCp-2 / 5
The whole point of my post was to make it easier to read. 3./5 does not look like a standard math equation. You need to know your audience: I don't think the poster(if they are having issues with the different of a real and int) is programming for high level science applications, so I would think simpler the better.
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.
3e+0 / 5
3 / 5e-0
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 putting a .0 after one of the divisors. This will convert them into floating point literals.
double f = 3.0/5.0;
this should fix your problem
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;
Integer versus floating-point division seems like a rite of passage; I know it was to me.