2

Division of two numbers using arithmetic operators in Java.

Scanner scan = new Scanner(System.in);
System.out.print("Write a number: ");
String mataett = scan.next();
System.out.print("Write a number: ");
String matatva = scan.next();

int nr1 = Integer.parseInt(mataett);
int nr2 = Integer.parseInt(matatva);
System.out.println(Math.round(nr1 / nr2*10.0)/10.0);

When I run this with 73/27 I get the answer 2.0, but what I want to get is the answer 2.7

Devendra Lattu
  • 2,732
  • 2
  • 18
  • 27
oneoe
  • 53
  • 1
  • 2
  • 8

3 Answers3

6

When I run this with 73/27 I get the answer 2.0, but what I want to get is the answer 2.7

The reason being you're getting the unexpected result is because when you divide by integers, the result is always an integer, which means any number after the decimal point is truncated.

nr1 / nr2 // <-- this part within the calculation is causing the problem.

A simple trick which you can do to overcome the problem is to multiply one of the integers nr1 or nr2 with 1.0 first then that should produce a double which should allow you to keep the precision because you're dividing by double now rather than int.

Example:

System.out.println(Math.round((1.0 * nr1) / nr2 * 10.0)/10.0);

Notice the 1.0

xlm
  • 6,854
  • 14
  • 53
  • 55
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
2

Change the line

System.out.println(Math.round(nr1 / nr2*10.0)/10.0);

To the line

System.out.println(Math.round(nr1 / ((double)nr2)*10.0)/10.0);

Because when you divide two integers, the answer is always an integer which is always rounder down ((int)2.9 = 2 and (int)3.1 = 3). cast into doubles and then divide in order to get the right answer.

Let's look at the following code:

int a = 10;
int b = 3;
System.out.println(a/b);

This will print 3, it will not print 3.3333333... that is because when dividing integers the result is always an integer and always rounded down. There are several ways to solve this

int a = 10;
double b = 3;
System.out.println(a/b);

This will print 3.3333333... because we are no longer dividing 2 integers, one of the variables is a double and therefor the result will be a double

Other ways:

  1. Cast into a double:

    int a = 10;
    int b = 3;
    System.out.println((double)a/b);
    
  2. Multiplying an integer with a double will result in a double and therefor this will also work

    int a = 10;
    int b = 3;
    System.out.println(1.0*a/b);
    

Notice that this will not work

int a = 10;
int b = 3;
System.out.println(a/b * 1.0);

This will not work because the division will be calculated before the multiplication and you will get the result 3.0 .

xlm
  • 6,854
  • 14
  • 53
  • 55
Donat Pants
  • 379
  • 4
  • 11
-3

Try the following:

double nr1 = Integer.parseInt(mataett);
double nr2 = Integer.parseInt(matatva);
Neil
  • 14,063
  • 3
  • 30
  • 51
cheyma
  • 1