int main()
 static short multiplycounter;
 static short dividecounter;
 double decimal;
 int rdecimal;
 cin >> decimal;
 rdecimal = int(decimal);
 cout << setprecision(10) << decimal << endl << rdecimal << endl;
 if(rdecimal % 1 != 0)
  while(rdecimal % 1 != 0)
   if(rdecimal % 1 == 0) { break; }
   multiplycounter = 0; 
   decimal = decimal * 10;
 }//if statement
 cout << decimal;
 cin.ignore(255, '\n');
 return 0;

Basically, I am trying to create a calculator that will take a number with a decimal part and change it into its fraction equal. I am having problems, though because I am trying to take the decimal number the use inputs, and multiplying it by ten until it has no decimal on the end. For example, if the user entering 12.745, I would multiply it by ten three times to get 12,745, and from there I could put that number over a denominator, and I could easily come up with that denominator by using the original number. For now at least, I don't have any problems there. But the real problem I'm having is how can I tell once I can stop multiplying the number by ten? My compiler complains when I try to use the modulus with a double or floating point value, and if I type cast to int, well, that obviously won't work either, because the decimal part is destroyed. What am I to do? :'(

Recommended Answers

All 5 Replies

I'm no math wiz, but here is another approach to consider:

Based on your above example of 12.745, you could extract the decimal portion, and put it over its place value. In this case, the .745 has precision to the 1/1000 place (the last digit is in the 'thousanths' position) Therefore, you can just set the numerator as 745 over 1000. Then what you have is a mixed fraction "12 and 745 over 1000."

in c++
12.745 == 12 + (745 / 1000);

mixed form
12 745/1000

12 149/200

if you want to reduce your fraction you'd probably need a function to test for prime, and one to perform the reduction.

Okay, I get what you are saying. That would make the amount of decimal places the program could work with a little bit larger, because the whole parts wouldn't have to be included. But then why doesn't this work:

static double decimal, pdecimal;
  cin >> decimal;
  int ndecimal;
  ndecimal = 
  pdecimal == decimal - double(ndecimal);
  cout << pdecimal;

Also (rdecimal % 1 != 0) is always false.
Maybe you should try parsing the number, for example:

int posdot;
int wyn=0;
char c;
      if (c=='.') posdot=i;
      else if(c<='9'&&c>='0') wyn=wyn*10+c-'0';
      else break;

Yeah, I solved that using fmod. But if you could take a look at my new problem =D

Ha, I'm an idiot, I figured it out. Anyone see what I did? HA, how stupid am I?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.