leigero
leigero

Reputation: 3283

Java's Math.pow() yielding bizarre results in simple case

I'm trying to do a simple programming challenge, and I'm running into a bizarre and unrelated issue with the Math.pow() function.

I'm getting that 6 to the power of 1 is 54?

I'm reading a file entered on the command line (via args[0]). That file contains only three numbers:

6
75
153

And the program I'm running is as follows:

public static void main (String[] args)throws IOException{

    File filename = new File(args[0]);
    Scanner file = new Scanner(filename);

    while(file.hasNextLine()){
        String numbers = file.nextLine();
        int numValue = Integer.parseInt(numbers);

        int sumOfPowers = 0;

        for(int i = 0; i < numbers.length(); i++){
            sumOfPowers += Math.pow(numbers.charAt(i), numbers.length());
            System.out.println(Math.pow(numbers.charAt(i), numbers.length()));
            System.out.println(Math.pow(6, 1));
        }

    }
    file.close();
}

The output this is generating is odd. Is it against Java rules to create a power function based on these types of values?

Output I get:

54.0
6.0
3025.0
6.0
2809.0
6.0
117649.0
6.0
148877.0
6.0
132651.0
6.0

Upvotes: 0

Views: 251

Answers (3)

Lokesh
Lokesh

Reputation: 582

Here numbers.charAt(i) returns a char '6' and NOT int 6.

value of char '6' in ASCII is integer value 54. '0' is 48, '1' is 49, and so on.

Just reset the counting from number 0.

Math.pow(numbers.charAt(i) - '0', numbers.length());

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533442

I think the main misconception here is that '6' != 6 If they were the same you won't need to have different literals. Instead the ASCII for '6' is (int) '6' or 54.

enter image description here

Upvotes: 8

Juned Ahsan
Juned Ahsan

Reputation: 68715

This is beacause the ascii value of character 6 is 54. Now check your code:

Math.pow(numbers.charAt(i)

Upvotes: 3

Related Questions