hii everyone ^^

My project for the c++ course is due tomorrow
but am facing a problem

this is the function

int  i=0,x , ar[100];
  double a_d,y=1;  

cin>>a_d;
  
 
  while (y!=0)
  {
  y=a_d*10;

  x=static_cast<int> (y)%10;
  cout<<endl<<"after   "<<y<<endl<<"the number  "<<x;
  a_d=y-x;
  i++;
  }
  cout<<i;
 
 
 
return 0 ; 
}

what I wanna do with the previose code is that

the user will enter a rational number
let say .001011 ( binary )

then the code will devied it into integers ( 0 0 1 0 1 1 )
and fill each subarray of arr with each number


ex 
arr[0]=0;
arr[1]=0;
arr[2]=1;

but for some reason when I run it the program gives an inifint loop

( am doing this so I can later convert it from decimal to binary )

thanx ^^

William Hemsworth commented: Code tags on first post. +11

Recommended Answers

All 4 Replies

Its an infinite loop because the value of y never changes.

>> x=static_cast<int> (y)%10;

The cast is unnecessary because y is already an int, and y%10 is also an int.

And why is d_a a double? Why not just enter the binary digits as an integer? (unless of course that is part of the assignment)

yes I have to do both interger and fractional part

but I didnt get how come that the y isnt changing
every time the y is the multiplication of the new a_d into 10 ?

thnx ^^

You could try walking through the program with a debugger or throughing in a bunch of output statements to monitor value of x, y, and a_d through a number of iterations to see if you can figure out what is wrong (of course it also helps if you've used a pencil and paper to see if the values spit out are the values you would have expected). That's what I would do since I agree that y isn't an int and its value does change each time through the loop.

If you step through the code and look at the values of y you will see that it never equals exactly 0 because y is a double and can contain small rounding errors such as 0.000000099. Never ever try to text a double against 0 because it will almost always fail. try something like while( y > 0.0000009)

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.