•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the C++ section within the Software Development category of DaniWeb, a massive community of 423,484 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 4,836 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our C++ advertiser: Programming Forums
Views: 254 | Replies: 2
![]() |
•
•
Join Date: May 2008
Posts: 6
Reputation:
Rep Power: 0
Solved Threads: 0
I'm dividing integers and making it a temporary double so i can get it in a decimal.
To have it with a fraction i just divide the numbers and cout the answer with the mod answer "/" num2. I want to display both the fraction and in decimal, so..
for 10 divided by 3, 3 1/3 is good, but 125 divided by 75 yeilds "1 50/75". How can i get if the simplify the fractions? i.e. " 1 2/3"
To have it with a fraction i just divide the numbers and cout the answer with the mod answer "/" num2. I want to display both the fraction and in decimal, so..
for 10 divided by 3, 3 1/3 is good, but 125 divided by 75 yeilds "1 50/75". How can i get if the simplify the fractions? i.e. " 1 2/3"
•
•
Join Date: Aug 2005
Location: near St Louis, Missouri, USA
Posts: 11,123
Reputation:
Rep Power: 38
Solved Threads: 929
just call modf()
I think it's about time we voted for senators with breasts. After all, we've been voting for boobs long enough. ~Clarie Sargent, Arizona senatorial candidate
Those who are too smart to engage in politics are punished by being governed by those who are dumber. ~Plato
Those who are too smart to engage in politics are punished by being governed by those who are dumber. ~Plato
•
•
Join Date: Oct 2007
Location: Cherry Hill, NJ
Posts: 1,876
Reputation:
Rep Power: 11
Solved Threads: 193
That won't help to reduce/simplify fractions so much as using the Greatest Common Divisor.
Here it is with the Euclidean algorithm, unrolled one iteration.
So, to simplify a fraction, simply:
Hope this helps.
Here it is with the Euclidean algorithm, unrolled one iteration.
C++ Syntax (Toggle Plain Text)
int GCD( int a, int b ) { while (true) { a = a % b; if (a == 0) return b; b = b % a; if (b == 0) return a; } }
So, to simplify a fraction, simply:
C++ Syntax (Toggle Plain Text)
void simplify( int& n, int& d ) { int gcd = GCD( n, d ); n /= gcd; d /= gcd; // If negative, make it the numerator. if (d < 0) { n = -n; d = -d; } }
Hope this helps.
![]() |
•
•
•
•
•
•
•
•
DaniWeb C++ Marketplace
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
Other Threads in the C++ Forum
- Previous Thread: BCB6 File Folder position and creation
- Next Thread: Elementary Class/const Question



Linear Mode