What am I doing wrong in Java Code Project 20 "Loan Calculator"? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What am I doing wrong in Java Code Project 20 "Loan Calculator"?

I need to output the loan to pay after 3 month. Every month the loan is paid by 10% of the remaining amount. E.g. 20000 ->10% = 2000 --> 18000 to pay. My code: import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int amount = scanner.nextInt(); //your code goes here for(int x=0;x<3;x++){ amount = amount - amount /100*10; } System.out.println(amount); } } Now the problem is, test cases 1 and 2 come back positiv but the hidden test cases (3-5) are false or wrong and I don't know why. Thank you in advance :)

10th Jan 2022, 3:51 PM
VollMax
VollMax - avatar
3 Answers
+ 4
I honestly can't explain why. but use this inside the for: amount -= amount*0.1; I suppose that with your way of doing it you lose a decimal at some point ... I can't think of anything else
10th Jan 2022, 4:36 PM
CGM
CGM - avatar
+ 3
Maximilian Gamed If you are interested you can read here about this issue: https://pmi-sesni.medium.com/floating-point-rounding-error-in-java-5c160cb55315 The very short answer is converting binary numbers to fractions or fractions to binary numbers causes troubles.
10th Jan 2022, 5:17 PM
Denise Roßberg
Denise Roßberg - avatar
0
I changed it to that and now it worked. I had it like amount =amount- amount*0.1; Before but I got an error so I sticked with divide by 100 multiply by 10. Thank you very much :)
10th Jan 2022, 4:40 PM
VollMax
VollMax - avatar