Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check a division as a int and float at the same time?

i have a question that goes with:

In Java, if we divide two integers, the result is another integer, but the result might not be correct. For example, 4/2 = 2, but 5/2 = 2.5 but in Java the result would be 2 when both 5 and 2 values are stored as integer values. The program should check if the numbers the result of the division is the same when the values are both integers and when they are floats.

So that I spend over 1 hour to figure this q but i have a problem with the ending part. What it meant in this part: "The program should check if the numbers the result of the division is the same when the values are both integers and when they are floats."

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import java.util.Scanner;
class StartUp2{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("Please type the first number that you want be devided: ");
        int a = sc.nextInt();
        float b = a;
        System.out.println("Please type another number that you want to devide with:");
        int c = sc.nextInt();
        float d = c;

    }
}

>Solution :

Do the division once with variables declared as int and once with float. Then compare the results.

int a = 42;
int b = 5;
float result = a/b;
float a = 42.0f;
float b = 5.0f;
float result = a/b;

Or as a self-contained function:

void compareDivision(final int a, final int b) {
  float intResult = a/b;
  float floatResult = (float)a/(float)b; // cast to float
  if (intResult != floatResult) {
    System.out.println("Results are different: " + intResult + " != " + floatResult);
  }
}

Building on the code from your updated question:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Please type the first number that you want be divided: ");
    int a = sc.nextInt();
    float b = a;
    System.out.println("Please type another number that you want to divide with:");
    int c = sc.nextInt();
    float d = c;

    float intResult = a/c;
    float floatResult = b/d;
    if (intResult != floatResult) {
        System.out.println("Results are different: " + intResult + " != " + floatResult);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading