I'm having problems with "int" in java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I'm having problems with "int" in java

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 int a=0; for(int x = 0;x<6;x++) { a = (amount/10); amount = amount-a; } System.out.println(amount); } } Above code is answer of java program in this app (loops section). In test case 100000 answer should be 53144 but my answer is coming 53145. I have figured out that problem lies at "a= amount/10". Here in last loop a value is coming 4.9 at ones place but code is converting it to 4 resulting my answer wrong. I tried ceil function, round off, making a double then converting it further to int but nothing worked... Please help

16th Dec 2020, 5:12 PM
Vishal Sharma
Vishal Sharma - avatar
8 Answers
+ 1
Vishal Sharma Take input as double Scanner scanner = new Scanner(System.in); double amount = scanner.nextDouble(); //your code goes here int i = 0; while (i < 6) { amount = amount - Math.ceil(amount * 0.1); i++; } System.out.print((int) (amount));
17th Dec 2020, 3:05 AM
A͢J
A͢J - avatar
+ 4
Vishal Sharma , use Math.ceil method. According to your code => a = Math.ceil (amount * 0.1).
16th Dec 2020, 5:36 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 1
Vishal Sharma Use Math.ceil like amount = amount - Math.ceil(a) System.out.println((int) amount);
16th Dec 2020, 5:36 PM
A͢J
A͢J - avatar
+ 1
I Am Groot ! Ya bro I already solved with this method but solo learn already mentioned amount as Int so I was thinking if anything can happen within those limits... Otherwise this is correct
17th Dec 2020, 3:11 AM
Vishal Sharma
Vishal Sharma - avatar
0
TheWh¡teCat 🇧🇬 I Am Groot ! I already tried to use that but error is occurring "possible lossy conversation from double to int" in this line having ceil function
16th Dec 2020, 5:43 PM
Vishal Sharma
Vishal Sharma - avatar
0
Vishal Sharma Declare a with double.
16th Dec 2020, 5:44 PM
A͢J
A͢J - avatar
0
for(int i = 0; i < 6; i++){ amount -= (amount * 0.10); } System.out.println(amount);
16th Dec 2020, 5:50 PM
Bahhaⵣ
Bahhaⵣ - avatar
0
I Am Groot ! When I'm declaring a as double then same problem is occurring as amount is int and we can subtract double from int also we can't change amount to double coz it is specially mentioned in question
17th Dec 2020, 2:20 AM
Vishal Sharma
Vishal Sharma - avatar