This question already has answers here:
Why does integer division code give the wrong answer? [duplicate]
(4 answers)
Closed last year.
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
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
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:
Cast into a double:
int a = 10;
int b = 3;
System.out.println((double)a/b);
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 .
Try the following:
double nr1 = Integer.parseInt(mataett);
double nr2 = Integer.parseInt(matatva);
Related
I know that in Python you can do floor division like this:
5 // 2 #2
The // is used for something totally different in Java. Is there any way to do floor division in Java?
You can do
double val = 5 / 2;
int answer = Math.floor(val);
OR
int answer = Math.floorDiv(5, 2);
If you were to call System.out.println(answer); the output would be
2
You can easily use Math.floorDiv() method.
For example:
int a = 15, b = 2;
System.out.println(Math.floorDiv(a, b));
// Expected output: 7
If you're using integers in the division and you cast the solution to another integer (by storing the result in another integer variable), the division is already a floor division:
int a = 5;
int b = 2;
int c = 5/2;
System.out.println(c);
>> 2
As khelwood stated, it also works with negative values but the rounding is done towards 0. For example, -1.7 would be rounded to -1.
use floorDiv()
int x = 10;
int y = 3;
System.out.println(Math.floorDiv(x,y));
There are many ways to convert a rational number into a decimal with a recurring part (in other words, 10/3=3.(3), where (3) indicates that it repeats forever). But these only work if the numerator and denominator are integers. What can we do if the numerator or denominator is a double? For example, how can we find that
1/0.3 = 3.(3)
UPDATE:
This works but only for int numbers.
http://www.programcreek.com/2014/03/leetcode-fraction-to-recurring-decimal-java/
Let split the problem in two pieces:
Convert 1/0.3 to N/M form
Convert N/M to a.b(c) form
Lets convert 0.3 to M/N form (which give us 3/10).
String input = "123.456";
String[] parts = input.split("\\.");
String whole = parts[0];
String fraction = parts[1];
int wholeInt = Integer.parseInt(whole);
int fractionInt = Integer.parseInt(fraction);
int multiplier = pow10(fraction.length());
int n = wholeInt * multiplier + fractionInt;
int m = multiplier;
System.out.println(n + "/" + m);
I used function pow10 which simply returns 10 power input.
Now we need divide 1 by 10/3 it is easy N1/M1 divided by N2/M2 it is simply (N1*M2)/(N2*M1).
We get our result in form N/M now (we also need to normalize it by dividing both part by GCD(N, M)
Now we ready to solve main problem.
First of all get whole part
int whole = n/m;
then find fraction and repeating part
int current = n%m;
StringBuilder sb = new StringBuilder();
List<Integer> controlSet = new ArrayList<>();
while((!controlSet.contains(current))){
int currentDigit = current *10 / m;
sb.append(currentDigit);
controlSet.add(current);
current = current *10 - m * currentDigit;
}
String fraction = sb.toString().substring(0, controlSet.indexOf(current));
String repeat = sb.toString().substring(controlSet.indexOf(current));
Here we just divide in loop getting result number by number.
Main trick then number starts to repeat when we meet current that we already use.
Now you need to take all parts together. Implement GCD (lots of implementation over internet).
This question already has answers here:
How to merge two int(s) into a double in JAVA?
(6 answers)
Closed 6 years ago.
Is there a way to force a number to be placed behind the decimal mark of a number?
Say I have a number = 2, and another number = 23. Is there a way for me to force 23 into 0.23, so that when I add the numbers I end up with 2.23? And is there a way to do this when the number of digits in the second number, in this case 23, are unknown?
EDIT:
I realize this was badly written. I am currently working on a program that converts from imperial units to metric units. Part of the code looks like this:
double feet = nextDouble();
double inches = nextDouble();
double heightInMeters = (feet + (inches/10)) / 3.2808;
The problem with this code is that I anticipate that the user only enters a value <0, 9> for feet. Is there a way to force the input for inches to something like 0.x where x = inches so that it doesn't matter if the number is greater than 9?
Would be lovely if it was possible without using toString() and parseInt().
You can get the number of digits in an integer, i, using:
1 + Math.floor(Math.log10(i))
(not ceil(log10(i)), since that calculates that 1 has zero digits)
You then need to divide i by 10 to the power of that number:
i / Math.pow(10, 1 + Math.floor(Math.log10(i)))
e.g.
23 / Math.pow(10, 1 + Math.floor(Math.log10(23))) == 0.23
Ideone demo
Alternatively, if you think those floating point operations log and pow are too expensive, you can determine the number of digits with a loop:
int d = 1;
while (d < i) d *= 10;
then
System.out.println(i / (double) d);
(noting that you need to cast at least one of the numerator or denominator to a floating point type, otherwise it will use integer division).
Try parsing to double like this, from a string:
Option 1
try
{
int n = 2;
int decimal = 23;
String full = Integer.toString(n) + '.' + Integer.toString(decimal);
double val = Double.parseDouble(full);
} catch (Exception e) //Or whatever exception
{
//Code
}
Option 2
Of course, there are simpler methods, like this:
try
{
int n = 2;
int decimal = 23;
double val = Double.parseDouble(n + "." + decimal);
} catch (Exception e) //Or whatever exception
{
//Code
}
I personally would recommend the solution directly above, since it is the simplest, and requires the least code.
Live Example for Second Option
Simple implementation using Strings:
public class Mainclass {
public static void main(String[] args) {
Integer num = 1546;
Integer num2 = 2;
String s = num.toString();
s = "0." + s;
Double d = Double.parseDouble(s);
System.out.println(num2+d ); // 2.1546
}
}
I want to make sure that initializationg of the float variable resultd is correct. Since it is where the error lies.
static void caculateValues() {
int a, b;
int resulta, results, resultm;
float resultd;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a:");
a = sc.nextInt();
System.out.print("Enter b:");
b = sc.nextInt();
{
//This is the only part I edited//
resulta= a+b;
results=a-b;
resultm= a * b;
resultd= a / b;
//This is where I stopped editing//
}
System.out.println("The result of adding is " + resulta);
System.out.println("The result of subtracting is " + results);
System.out.println("The result of multiplying is " + resultm);
System.out.println("The result of dividing is " + resultd);
}
They claim my output should looks something like this:
(a = -50) (b = -20)
The result of adding is -70
The result of subtracting is -30
The result of multiplying is 1000
The result of dividing is 2.5
But supposedly my input shows:
The result of adding is -70
The result of subtracting is -30
The result of multiplying is 1000
The result of dividing is 2.0
Even if resultd is a float, you are still dividing two ints:
a / b
In Java, division of 2 ints must be an int. That is why 2.0 is showing up. -50 / -20 is 2, not 2.5 in Java. Only after the 2 is generated is it promoted to a float upon assignment to resultd.
Cast one of the variables to a float to force floating-point math from the start.
resultd = (float) a / b;
You could just as easily make resultd a double and cast a to a double instead.
The output of below code in Java is 3.0.
Why isn't it 3.3333333...?
double a = 10 / 3;
System.out.println(a);
Because int / int returns an int (regardless of what you assign it to afterwards).
So 10 / 3 returns 3 (integer division rounds down).
This would only then get converted to double.
To fix this, make one of the values a double (so it's double / int, which returns a double):
double a = 10.0 / 3;
or
double a = (double)10 / 3;