Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The below code wont execute with some inputs

Tags:

java

Sorry for such a basic level question guys. But I'm starter in programming. Not a computers guy. So kindly help me. In this code when I give input 1000000000, 1000000000, 999999999 the answer should be 4. But my answer is 1. I expect the if statement to execute but it is not executing here.

if you take m*n as a room and "a" as the side as a square tile. Then I want to count MINIMUM no. of tiles required to fill the floor of room. tiles may cover a bit more area but should not leave the room empty. this is my objective. It's working with inputs like 6,6,4 or 15,20,13 etc.

Now its working guys. I had posted the correct code with those minor changes below.

import java.util.Scanner;
public class TheatreSquare {
    private static Scanner input;
     public static void main(String[] args) {
     input = new Scanner(System.in);
     float m=input.nextFloat();
     float n=input.nextFloat();
     float a=input.nextFloat();
     long i=(int)(m/a);
     long j=(int)(n/a);

     if((a*a*i*j)<m*n){

        if(a*i<m){
            //to check weather it is entering if()
            System.out.println("true");
            i+=1;
        }
        if(a*j<n){
            System.out.println("false");
            //to check weather it is entering if()
            j+=1;
        }
       }
       System.out.println((double)(i*j));
     }
 }
like image 974
Krishna Avatar asked Feb 11 '23 00:02

Krishna


2 Answers

Your floats are overflowing when you multiply them. Defining m, n and a as doubles will solve the issue:

double m = input.nextDouble();
double n = input.nextDouble();
double a = input.nextDouble();
like image 112
Mureinik Avatar answered Feb 15 '23 10:02

Mureinik


The int conversion loses precision.

Here in this case, a*a*i*j is equal to m*n Hence the if loop will not execute. Also a*i is equal to m and a*j is equal to n. Hence i isi and j is 1, so i*j is 1. Look at this

You need to allow it to go if it is equal too. Replace

if((a*a*i*j)<m*n){

        if(a*i<m){
            //to check weather it is entering if()
            System.out.println("true");
            i+=1;
        }
        if(a*j<n){
            System.out.println("false");
            //to check weather it is entering if()
            j+=1;
        }
       }

with

if((a*a*i*j) <= m*n){
        System.out.println("Entered if block");
        if(a*i <= m){
            //to check weather it is entering if()
            System.out.println("true");
            i+=1;
        }
        if(a*j <= n ){
            System.out.println("false");
            //to check weather it is entering if()
            j+=1;
        }
        System.out.println("i is:"+ i +"j is:"+j);
       }
like image 27
Uma Kanth Avatar answered Feb 15 '23 09:02

Uma Kanth