java - Unable to obtain the correct product of numbers when used with Math.pow() -
i trying write recursive function gets string , returns integer form of it. know can done in java using integer.parseint
. part of exercise doing.
for following code, when enter "963" input, returns output "6291". so, checked if array getting passed , was.
to check multiplication, split , printed product each time, gave 5700, 540 , 51, correctly sum 6291. (which should have been 900 + 60 + 3 = 963). i'm unable figure out wrong in program.
import java.io.*; import java.lang.*; class recconvert { static double i=0; static double sum=0; public static void main(string[] args) throws ioexception { bufferedreader b = new bufferedreader(new inputstreamreader(system.in)); string input = b.readline(); int number = recursiveconvert(input); system.out.println("the number "+number); } static int recursiveconvert(string input) { char[] chararray = input.tochararray(); if(i < chararray.length) { sum = sum + (chararray[(int)i]) * ( (double)math.pow(10.0,chararray.length-i-1) ); i++; return recursiveconvert(input); } else return (int)sum; } }
this problem (chararray[(int)i])
. you're multiplying char
double. character.getnumericvalue(chararray[(int)i])
solve it.
Comments
Post a Comment