Home > Back-end >  How to check a division as a int and float at the same time?
How to check a division as a int and float at the same time?

Time:10-24

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."

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;

    }
}

CodePudding user response:

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);
    }
}

CodePudding user response:

If you were to divide integers 5/2, then you would end up with 2.

Reverse the operation, multiply the result by the divisor, 2 * 2, and you end up with 4. Therefore your program should return false since it didn't equal the dividend, 5.

  •  Tags:  
  • java
  • Related