Sinisterly
Fractions in C++? - Printable Version

+- Sinisterly (https://sinister.li)
+-- Forum: Coding (https://sinister.li/Forum-Coding)
+--- Forum: C, C++, & Obj-C (https://sinister.li/Forum-C-C-Obj-C)
+--- Thread: Fractions in C++? (/Thread-Fractions-in-C)



Fractions in C++? - Skipperdoo32 - 09-13-2011

I was writing a primitive program involving solving a random equation, and I noticed that when I entered:

long double y;
y = (1/5) + (2/8);

cout << y

The computer could not read the fractions, and it only worked when I changed it to decimals. Is there any way to use fractions in C++, or is it limited to significant figures?


RE: Fractions in C++? - Frooxius - 09-14-2011

What you used in the expression are integer literals, so integer math was performed - it's way faster, but doesn't support fractions. To solve this, simply use double literals:

Code:
long double y; y = (1.0/5.0) + (2.0/8.0); cout << y;

Also, long double is kind of unnecessary, in fact, even float has enough precision for this - don't waste space and performance. You can use float literals:

Code:
float y; y = (1.0f/5.0f) + (2.0f/8.0f); cout << y;



RE: Fractions in C++? - MR.AWESOME - 09-17-2011

All you have to do is do that thing like this
long int y = (1/(5*1.0)) + (2/(8*1.0));