Login Register






Thread Rating:
  • 0 Vote(s) - 0 Average


Fractions in C++? filter_list
Author
Message
Fractions in C++? #1
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?

Reply

RE: Fractions in C++? #2
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;
I love creativity and creating, I love science and rational thought, I am an open atheist and avid self-learner.

Reply

RE: Fractions in C++? #3
All you have to do is do that thing like this
long int y = (1/(5*1.0)) + (2/(8*1.0));

[Image: mrawesome.gif]

Reply







Users browsing this thread: 1 Guest(s)