integer to fraction conversion.

Started by
14 comments, last by GekkoCube 22 years, 2 months ago
Evilcrap, I am assuming you mean:

float x = value;
while(x > 0.0f)
{
x = x / 10.0f;
}

This way we can actually get a fractional value instead of the quotient from simply dividing.
Again, I am assuming you mean this..?

How do you place code snippets in a nice block of color???


I was trying to get this offset due to a project im working on.
It has very little or no meaning in an actual game...but let''s just say I had to do this!

thanks.

~ I''''m a wannabe programmer ~
Advertisement
GekkoCube, your while loop will either finnish immediately, or never finnish.

If x is positive, then x will never ever become less than zero if you keep on dividing by 10 (a positive number divided by a positive number is never a negative number). In that case, the while loop will never exit.

If x is negative, it will exit before it enters, since x is less than zero when the loop starts.

PS. You put code between the [ source ] and [ /source ] tags (without spaces in the tags, of course).
again i dont see the relevance to using mod and fractions. if you are simply trying to take a whole number and making into the greatest fraction below 1.0 that has a divsor that is a power of 10 then use evilcraps method or the other method shown (both work well). though to correct EvilCrap AND GekkoCube

  while(x>=1)   x/=10.0f;  


whether this is fatser or not however is up in the air. i have not done a benchmark no care to since this has not too many uses in game development. in homework however...
Always always always do reciprocal multiplication if you can.

If you''re doing anything like either of these:
  double* arr = new double[1024];for(size_t i = 0; i < 1024; ++i){    arr[i] /= 10.0;}  

or
  double* arr = new double[1024];double div = calculateSomeValue();for(size_t i = 0; i < 1024; ++i){    arr[i] /= div;}  

Then calculate the reciprocal outside the loop and multiply.

Reciprocal multiplication is significantly faster than division (such that you only need to loop a small number of times for it to be worthwhile).
char a[99999],*p=a;int main(int c,char**V){char*v=c>0?1[V]:(char*)V;if(c>=0)for(;*v&&93!=*v;){62==*v&&++p||60==*v&&--p||43==*v&&++*p||45==*v&&--*p||44==*v&&(*p=getchar())||46==*v&&putchar(*p)||91==*v&&(*p&&main(0,(char**)(--v+2))||(v=(char*)main(-1,(char**)++v)-1));++v;}else for(c=1;c;c+=(91==*v)-(93==*v),++v);return(int)v;}  /*** drpizza@battleaxe.net ***/
    while(fabs(x) >= 1)    x *= 0.1f;  


Should make it correctly.


Edited by - darookie on January 30, 2002 5:01:37 AM
GekkoCube : i figured out how to do it by selecting a post and going to edit... try it out...
  blah blah  

This topic is closed to new replies.

Advertisement