0

im trying to make a logarithm calculator and ran into a problem where my program is starting off from 0.099999 not from 0.0 when incrementing by 0.1 to find the power so the right result is getting skipped as it is not an exact value( I know I probably have the worst algorithm possible but I'm still experimenting with new things ).

import java.util.*;

public class Main{
public static void main(String args[]){

    double base = 0;
    double answer = 0;
    double answer2 = 0;
    double power = 0;
    Scanner x = new Scanner(System.in);

    System.out.print("Enter base: ");
    base = Double.parseDouble(x.next());

    System.out.print("\nEnter answer: ");
    answer = Integer.parseInt(x.next());


    if(answer != 1){

    while(answer2 != answer){

        power +=0.1;
        answer2 = Math.pow(base,power);
        System.out.println("power: " +  power + " answer: "+ answer2); 

    }

}

    System.out.println("the power is: " +power);



}

}

Blaze
  • 55
  • 1
  • 8
  • That's how floating point works sometimes. Now what is your question? – Joe C Nov 02 '17 at 22:15
  • Don't increment `power` by `0.1` (which can't be represented exactly); increment it by `1` (which can be represented exactly), and then call `Math.pow(base, power / 10)`. – Andy Turner Nov 02 '17 at 22:17

0 Answers0