C++, issues with converting a decimal to fraction

Hi all,
I am working on a C++ program that converts a decimal to a fraction, finds the lowest common multiple, multiplies the numerator by the denominator, then reduces the fraction again so the fraction will be 'numerator/1'. 
I am using this code in a larger program to change a floating point slope value to a whole value for slope-intercept equations and standard form equations.
The program will run but I tested almost 500 numbers and 20 numbers made the program crash (it stalled and did not finish the equation, I had to close the terminal and open it up again... )
These 20 numbers I had problems with:
2.36,  7.36,  1.11,  1.001,  1.66,  1.88,  2.22,  2.13,  3.24,  3,26,  3.32,  3.43,  3.49,  3.51,  3.57,  3.68,  3.74,  3.76,  3.82 
(I am sure there are more...)
I have tried c-style casting and dynamic and static casting to try to resolve this issue. Can someone help me out and point out why these certain numbers make the program crash and offer a possible sloution?
I tried debugging this program on gdb and keep on getting this frustrating message..
(gdb) break 16
No line 16 in file "init.c".
(gdb)
Here is the program's code:
//example.cc
#include <iostream>
#include "reduce.h"
#include "decimal-to-fraction.h"
using namespace std;
int main()
double deci;
double n, d;
while(1) {
cout << "Enter a decimal to convert to a fraction ('0' to quit): ";
cin >> deci;
cin.ignore(INT_MAX, '\n');
if(!deci) exit(0);
dec_to_frac(deci, n, d);
if (n * d != n){
cout << '\n' << deci << " = " << n << '/' << d << "\n\n";
cout<<'\n' << d << " x " << n;
n = d * n;
cout<< " = " << n << "\n\n";
cout<<'\n' << n << '/' << d;
reduce(n, d);
cout << " = " << n << '/' << d << "\n\n";
cout<<'\n' << n << "\n\n";
else
cout<<'\n' << deci<< "\n\n";
return 0;
#ifndef _REDUCE_H_
#error You must include "reduce.h" before this file
#endif /* def _REDUCE_H_ */
#ifndef _DECIMAL_TO_FRACTION_H_
#define _DECIMAL_TO_FRACTION_H_
void dec_to_frac(double decimal, double &numerator, double &denominator)
//numerator = static_cast<int >(decimal);
//numerator = (int )decimal;
numerator = decimal;
denominator = 1;
while(numerator != (int)numerator) {
numerator *= 10;
denominator *= 10;
reduce(numerator, denominator);
#endif /* def _DECIMAL_TO_FRACTION_H_ */
#ifndef _REDUCE_H_
#define _REDUCE_H_
void reduce(double &numer, double &denom)
int i;
for(i=2; i<=numer; ++i) {
if( ((numer/i) == ((int )(numer/i))) && ((denom/i) == ((int)(denom/i))) ) {
numer /= i;
denom /= i;
--i;
#endif /* def _REDUCE_H_ */

Okay, a few things ('cause I'm picky too):  LCM == "least common multiple" or "lowest common multiple", it's really interchangable.  LCD == lowest common denominator, which is when you're adding two fractions and want to find the lowest denom.  Now that we have that out of the way...
Using ++i or i++ as the third expression in your for loop will make zero difference. 
for (int i=2; i<=numer; ++i)
will have exactly the same effect as
for (int i=2; i<=numer; i++)
, though they may have slightly different performances.  The reason for this is that the third expression (i++ or ++i) is evaluated after every iteration of the loop, meaning it doesn't happen until the end of the loop body is reached, and then it's evaluated independently, meaning all you end up with is 'i' incrementing.
As for this:
if( ((numer/i) == ((int )(numer/i))) && ((denom/i) == ((int)(denom/i))) ) {
becomes
if (numer % i == denom % i == 0) {
That's about right, it would look more like
if (numer %i == 0 && denom % i == 0)
- the other way would probably not behave the way you expect.
Some other tips:
numer and denom should be 'int' or 'long' - not double.  You don't expect your numerator and denominator to have decimal points, so use integral types - using floating point 'double's is likely what's getting you into this trouble -- floating point arithmetic is inherently imprecise.  You might have better luck parsing the input yourself and constructing the numerator from that instead of reading directly into a floating-point number.
I'm hacking around with your code right now for fun; I'll let you know if I find anything.
==edit==
Oh, something else I wanted to mention; to break on a line in gdb you type:
break filename:linenumber
ie.
break example.cc:16
Last edited by Cerebral (2007-06-03 02:43:42)

Similar Messages

  • Issue with display of decimal places

    Hi,
    In our custom built components we are facing a strange issue with the display decimals  where the data type of an element is "QUAN - Quantity field, points to a unit field with format UNIT".
    If the element has a value of 3000.000 KG the value is displayed as 3000. Where as for an element which has a value 3000.123 KG the same is displayed as it is with the decimals. We tried to resolve the issue by using Text editor or Input field as read only but in vain. The display property in the context are set to default.
    If we change the element data type reference to "Dec - Counter or amount field with Comma and Sign" then all the values are displayed with the decimal places even if decimals are zero.
    As a result we are facing alignment issues for the various quantity related elements displayed on the screen.  To change the underlying data type of the element is a not a solution for us as the data type quan is required for conversion from one unit to another unit.
    Can someone please advise how we could resolve this issue.  We are on NW 7.0 + EHP4 + NW 7.01 SP4, kernel patch level 55 for 7.01
    Regards
    Rohit Chowdhary

    Jameel, Thanks for the answer but this is a not a solution for us. We have around 40-50 webdynpro components and with mutliple views referring to this data element / domain combination. More so the context are bound to database tables / structures . 
    I hope to get a reply from Thomas on possible solution for this. I am not sure if I can open an support ticket for this issue.
    Rohit Chowdhary

  • Issues with converting to PDF and zoom size

    I've created a Captivate file and converted this to Adobe PDF - when we have tested the output we notice a white edge on the left and bottom side of the document and encounter issues with 'zoom' on pdf - when its 100% its fine (apart from the white edge), but when we reduce the zoom it covers the project and exposes only a small amount of it.
    Any ideas?

    I've created a Captivate file and converted this to Adobe PDF - when we have tested the output we notice a white edge on the left and bottom side of the document and encounter issues with 'zoom' on pdf - when its 100% its fine (apart from the white edge), but when we reduce the zoom it covers the project and exposes only a small amount of it.
    Any ideas?

  • Issues with converted Inkscape SVG files

    I've been downloading a lot of SVG files, most of which were created with Inkscape, from openclipart.org recently. I've had to open them in Illustrator and save them in .ai format before placing them in an InDesign document as InDesign doesn't accept SVG files as a link.
    My problem is that some of these SVG files that I've converted to .ai don't display properly when I place them into InDesign. I can see the bounding box of the linked files, but nothing inside. I'm pretty sure this has only happened with files that I have edited a little after bringing them into Illustrator. The edits haven't been anything major - just changing colours and adding transparency masks here and there as sometimes some of the SVG gradients and mask/transparency effects are lost when I open them with Illustrator.
    I've tried re-saving the SVG files from openclipart.org and doing a save as in Illustrator to force it to reconstruct the file, but with no luck. Here is an example of one of the troublesome SVGs: http://openclipart.org/people/Gerald_G/Gerald_G_Lemon_Variations_2.svg
    Does anyone know why this is happening?

    It seems like restarting InDesign has fixed the issue. Still, I have one particular file which does this every time I try to place it, even after restarting InDesign.

  • Urgent.  Issue with converted .mov files to avi not working in Premiere.

    I am trying to import video files that I have converted from .mov to .avi through OjoSoft Total Video Converter and anytime I try to put a file into the work area, the video goes to Video 1, and Audio goes to Audio 4.  When I try to play it I get no audio, and the video jumps from frame 1 to frame 2.
    Does anyone know a good converter or know the best way to convert and what filetypes to do so?  They work converting them as MP4 video files, but I like avi's better.
    I have tried converting the .mov to mpeg4 and H.264 (Both with audio as MP3).  They will play in Windows Media Player after convert but not in premiere...
    I am running Premiere CS4 on Windows7 with no direct codec packs installed.  I opened a video/audio file that I worked on before with no issues...video/audio run flawlessly in Premiere.
    Please help!

    What are the codecs in the original MOV files and what are the codecs after conversion? Use GSpot to identify them.

  • Issues with Converted Project

    Hello,
    We have an HTML project that was written using RoboHelp 7.
    The Primary Output/Layout is Microsoft HTML Help (.chm file). Our
    office recently downloaded a trial version of RH 8 and we tried
    opening the project with the new version (yes we have backup copies
    of the project!). Upon opening the project and checking it over,
    we've noticed odd problems with the color of the hyperlinks
    changing without selecting them (all of the hyperlinks and
    bookmarks appear to change to the default purple color in a topic
    by clicking on another topic and then clicking back to the first
    topic), and little red square boxes appearing where a Shift/Enter
    was used.
    My concern is that the project had had to be rewritten when
    we got RoboHelp 7 and converted from RoboHelp 4. At the time, when
    we first opened the project in RH 7, we found corruption in text
    and bullets that were gigantic. After trying to correct/resolve
    these issues without success, we made a decision to recreate the
    project from scratch.
    Can anyone shed some light on what is happening or what we
    are doing wrong? We've not had this problem with our Webhelp
    (Primary Output Layout) projects.
    Thank you,

    Isn't this the same question that was asked about 30 minutes
    ago in the thread linked below?
    Click
    here
    Please don't cross post the same question to multiple forum
    categories.
    For anyone choosing to reply, please reply to where the
    question first appeared and not here.

  • Issue with converting string to date object

    Hi all,
    I have a problem with sorting a list of dates in a table column. My dates are in the format 'yyyy-Mmm-dd'(Eg: 2009-Dec-23). Can someone help me how to sort the dates in this format. here is the code which i tried.
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-Mmm-dd");
              Date d1= new Date();
              Date d2= new Date();
              try {
                   d1 = dateFormat.parse("2006-Jun-09");
                 d2 = dateFormat.parse("2006-Apr-10");
              } catch (ParseException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              System.out.println("converted date 1"+ d1);
             System.out.println("converted date 1"+ d2);
    Exception : Unparseable date: "2006-Jun-09"
         }Please someone help me how to pass this date in the right format.

    I believe twisai may have lost the documentation so he/she can figure this out rather than guess that "Mmm" means 3-letter month, first letter capitalized. Let me remind him of the link:
    [http://java.sun.com/javase/6/docs/api/index.html]

  • Issue with printing the decimal value in smartforms

    Hi experts,
    Here I am printing the net valve in to smartforms.The problem is, valve i want to print is 4505.600.But it is displaying as 45056.00.It is in OMR currency. This problem occurs only for this currency.i am picking the value from PO.
    I have used komv-kwert feild for display. Please give me the solution
    Regards,
    madhu

    Hi Madhu,
    I have faced similar problem in my Smartform with currency JPY with no decimal places at all.
    To resolve this you have to specify Reference Currency with the Currency type  under Global Definitions-->Currency/Quant.Fields. For example take your case :
    Fieldname               Reference Field     Data Type
    WA_FINAL-KWERT              W_WAERS           C CURR
    *Here W_WAERS should contain OMR
    *WA_FINAL-KWERT sould contain 45056.00 then your output will look like 4505.600
    Thanks & Regards,
    Rock.

  • I am having issues with converting some DVD to Video and getting it to load on iPad

    I have used Format Factory to convert a DVD to Video - It will play on Computer, and load into iTunes but will not load on to iPad? 

    Click on the video in itunes and then click on the Advanced Menu option at the top, and click on "Create iPad or Apple Tv version".
    This will create a file optimized to play on the iPad. Then just sync that version over.

  • Urgent:Issue with converting mx: Application to S: application

    Hello,
      I am currently trying to migrate a flex 3 project to Flash4...but when I replace <mx: application> to <s: Application> it gives following answer:
    Could not resolve <s:Application> to a component implementation.
    I have included the ur;s and libraries such as :
    xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx"
    Also I have used  following to implement swiz framework:
    xmlns:control="edu.mizzou.firefly.control.*"    xmlns:view="edu.mizzou.firefly.view.*" xmlns:core="edu.mizzou.firefly.view.core.*" xmlns:swiz="http://swiz.swizframework.org
    Please can any one suggest me where I am going wrong?? Any help would be highly appreciated
    Thanks
    Akshay

    The SDK version is Flex4....Am I supposed to make any  changes there??? Also I observed that in the application declaration below:
    <s:Application frameRate="30" layout="absolute" backgroundGradientAlphas="[1.0, 1.0]"
        horizontalScrollPolicy="off" verticalScrollPolicy="off" backgroundGradientColors="[#000000, #323232]" addedToStage="stageHandler(event)"
       xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx">
    Some of the mx component doesn't work as intended in Flex 4 such as
    layout= mx.Core.LayoutContainer
    backgroundGradientAlphas=mx.Core.Application
    horizontalScrollPolicy,verticalScrollPolicy=mx.Core.Container
       I am looking into the documentation of Flex 4 but I am not able to find any solutions to them
       Any suggestions from your side??

  • Color replacement issue with converted RGB mode picture

    I am new to Photoshop.  Opened a bmp file using PS CS5.5, and changed its color mode from Indexed to RGB, 8bits/channel.  Tried to use the color replacement tool to replace a darker shade of red (127, 0, 0) to a slightly lighter one (186, 0, 0), but it would not replace it -- not that it popped out any errors, but it just didn't do anything.
    The tool settings are:
              spacing: 1%,
              hardness: 100%,
              Mode: color,
              Sampling: background swatch,
              Limits: discontinguous,
              Tolerance: 1%,
              Antialias: off
    foreground: 186,0,0
    background:127,0,0
    so I tested by choosing pure white:
    foreground: 255, 255, 255
    background: 127,0,0
    it did make a difference, however, instead of pure white, it was some kind of dark gray: 38, 38, 38.
    so I am just wondering if this is a bug, or if I did something wrong.  Thanks!

    Use the Filter Factory plug-in, Enter the following code in the red box. Leave the green and blue boxes alone
    r==127  &&g==0  &&b==0 ? 187:r

  • Conversion of book dimension from decimal to fraction

    Hi,
    I am a crystal report developer and new to SAP R3 environment.  I am creating reports with SAP BW queries as source.  I am working for a publishing client.  They are storing the material (Book) details in the SAP system (Material table).   SAP has a provision to capture physical properties of the book like width, height and thickness.  They are entering details upto 3 decimal places precision in inches or in specified unit of measure. 
    When some extracts are generated from SAP System the values like 10.380 is converted as 10-3/8.  But the actual 10-3/8 value is 10.375.  The rounding is not uniform when I checked with few other values.  I came to know from SAP experts these conversion are happened in an IDOC.  I don't know much about this.
    Can anyone help me in this conversion logic.  Since I have to implement the same in my Crystal report.  My BW query is just giving it in the decimals, my users are interested in seeing it as fraction since the other exports from SAP is showing it in fraction.
    Thanks and Regards,
    Subbu S.

    In the user exit of Outbound Idoc, they might have used some custom logic to implement the given logic.
    It may vary on other factors as well. In your case, that should be verified or cross checked in your system only.
    For converting the decimal to fraction in SAP, you can refer the below function module.
    'CONVERT_TO_FRACTION'

  • Issue with Backflush when Consuming Fractions

    I am having an issue with back-flushing I was hoping Guru's  could help me .
    Here is the issue:
    In the BOM for every 1 EA of X(Parent) we need .025 EA of Y(Child)
    The parent part is X. Using CS03 and typing in a quantity of 20 pcs everything looks perfect. I would consume component Y .500 of a sheet.
    If you review MFBF for 20 pcs. of X  it wants to consume 1.00 of Y. (1 whole sheet instead of .5)
    I know I could put a rounding value of 40 on the X to fix this but that would not be an option for this particular process. Measurements of each of these is not exactly the same and very critical.
    Is there an issue with SAP consuming fractions? It seems to round up to 1 whole sheet when it should only consume .500 of a sheet. Do you know of a way to fix this?
    Any info would be greatly appreciated
    Thanks,
    Safi

    For some reason which is unknown for me, this topic is very hard to manage within SAP.
    We face exactly the same issue producing Tanks from steel sheets.
    Base Unit of Measure was EA for Sheets . SO, we create a copy of EA called ED (each with decimals) , allowing up to three decimals and assign it as an alternate UoM to the material. In Bom, we had, for instance, 3.6 ED to produce a tank.
    But, in reservations the quantities are stored as Base Unit of measure and without decimals, regardless the fact that you a have an alternative UoM , etc etc.
    So, if you consume the component based on MIGO and reservations, SAP will propose 4 EA (o 4 ED ! which is even stranger - because of double conversion between base and alternative UoM) . If you consume by backflush, you dont even realise that the GI is being carried out in that way.
    We are still waiting for some solution after we sent a message, describing the issue. It is advisable to search the SAP Notes to see if there is some solution .
    So far, alternative UoM is not the solution.
    You must change the base unit of measure to ED or have some manual procedure of checking the quantities.
    Of course, EA can be redefined with decimal parts, also, but this normally can lead to some other problems (other parts managed striclty in EA, i. e. a tank,  could be managed in fractions, 0.75 of a tank !!! etc. )

  • Issue with document text - converting from PDF to Word

    I have used Adobe Reader in the past with no issues.  Today, I tried to convert a PDF to a word document.  It worked, but the text all changed to wingdings font (even though it says it is Calibri).  Any suggestions?

    Hi marleighp23001196,
    Are you facing this issue with a specific file or with other word files too?
    Regards,
    Rahul

  • Issue with SQL converter: Query Migration Tool for Microsoft SQL Server to SAP HANA

    Hello,
    I found the following blog : http://scn.sap.com/community/business-one/blog/2013/04/10/how-to-convert-sql-from-ms-sql-server-to-sap-hana
    I am trying out this migration tool for converting my MS SQL queries to HANA.
    I am running into issue while converting certain queries.
    The issue is specific to "set" commands which set local variables inside "create procedure" commands.
    e.g.
    a standalone set command:
    SET @var = (SELECT TOP 1 name FROM mytable ORDER BY name)
    is converted well:
    SELECT (SELECT TOP 1 "name" FROM "mytable" ORDER BY "name") INTO var FROM DUMMY;
    But when the same is part of create procedure:
    CREATE PROCEDURE [dbx].[XXXXX_YYYY_ZZZZ]
    AS
    SET @var = (SELECT TOP 1 name FROM mytable ORDER BY name)
    it fails in converting the same:
    --Statements in the input file contain errors; conversion was canceled
    I would like to understand who can help me here.
    Thanks...

    Hi Mayur,
    that tool cannot convert stored procedures. it is still being developed. For these you have to do it manually.

Maybe you are looking for