public static void main(String[] args)
{
   Scanner in = new Scanner(System.in);
   System.out.print("Input an integer: ");
   int n = in.nextInt();

   int d = 1;
   int temp = n;

   while (temp > 9)
   {
      temp = temp / 10;
      d++;
   }

   System.out.println(n + " can be expressed in " + d + " digits");
}

here's what we're supposed to do:
The fractions 1/2, 1/4, 1/8 get closer and closer to 0 as they are divided by two. Change the previous program to count the number of divisions by two needed to be within 0.0001 of zero.

All I could really come up with was this:

int temp = 1;

   while (temp > 0)
   {
      temp = temp / 2;
      if (temp == 0.0001)
      	break;
      d++;
   }

   System.out.println(d);

But I'm just an extreme beginner and I don't know how to solve it...

Recommended Answers

All 3 Replies

your code is very close, just do this

int temp = 1;
int d = 0;
while (temp >0.0001){
   temp = temp /2;
   d++;
}
System.out.println(d);

this will loop until temp < 0.0001 which is exactly what you want.

It didn't work for a sec, but then I realized that temp needed to be a double. Thank you so much!

sorry about that

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.