Double divided by double java

How to divide an integer by double?

That’s a different question than the title; that’s not integer division, that’s getting the integer part of the result of floating point division. » If you need the symmetric version (truncation towards zero), you’ll have to handle negative quotients: Solution 2: To force integer division, use or (for the calculation part); would probably be the better choice: That uses an explicit cast back to for emphasis; you can just write it with the implicit cast back to if you prefer: Do note that on a non-zero can result in (for instance, if is ), which then ends up being division-by-zero and thus a runtime exception.

How to divide an integer by double?

Should be 213,3333333. , but is 320.0 . why?

int integ = 320; System.out.println((double) integ / (double) (3/2)); 

I mean: I’m using double, why do I get integer?

3/2 is int division, which results in 1 (and casting it do double results in 1.0 ). Therefore you are dividing 320 by 1.0 .

Use 1.5 instead (or 3.0/2 if you must).

You are doing the casting to double after the division, which is executed with integer arithmetic. The easiest way to force floating point arithmetic is by making one of the operands a double:

int integ = 320; System.out.println((double) integ /(3.0/2)); 
int x = 3; int y = 2; System.out.println((double) integ /(1.0*x)/y); 

Java — Integer division: How do you produce a, Nothing bad will happen when you cast an int to a double. If you’re just not sure of how it works, look it up in the Java Language Specification. Casting an int to …

Читайте также:  pdf test

Force integer division on a double?

Where x & y are both double

I would like x to be the integer part of x/y , how do I do this?

But am receiving a double cannot be dereferenced error in TIO which I presume means the double x does not have that method

IO x = x\y : Carry out float division then round towards -∞

Sample table

NB all I’m after is to change this code to add in floor division with \

Relying on some Math function is arguably the best choice. «Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.»

If you need the symmetric version (truncation towards zero), you’ll have to handle negative quotients:

To force integer division, use int or long (for the calculation part); long would probably be the better choice:

That uses an explicit cast back to double for emphasis; you can just write it with the implicit cast back to double if you prefer:

Do note that (long)y on a non-zero y can result in 0 (for instance, if y is 0.3 ), which then ends up being division-by-zero and thus a runtime exception.

I would like x to be the integer part of x/y

That’s a different question than the title; that’s not integer division, that’s getting the integer part of the result of floating point division. If that’s what you want, just cast the result:

. (and of course the long is then implicitly cast back to double ) or use Math.floor on it.

Right. x is a double , not Double . Primitives (like double ) don’t have methods, only reference types (like Double ) do.

If a smaller data type is assigned to a bigger data type, there’ll be no error. But the assignment of bigger to smaller gives error. In this case, you need to make compatible these data types with each other using Type Conversion (‘ x = (Type) y ‘). Converting a double to int is an example of assigning a bigger data type ( double ) to smaller ( int ). When we perform this operation, the double variable lost its precision and its «integer part» is assigned to the int variable.

double x = 3, y = 2; x /= y; int integerPart = (int) x; System.out.println(integerPart); // Prints 1 

From small to big, the numeric data types are as follows btw:

Edit: After your last edit I realized what you actually ask. Your first expression was wrong. You don’t want to find integer part of the double result of division, you want its floor. Just use java.lang.Math.floor :

double[] x = ; double[] y = ; for (int i = 0; i < y.length; i++) < for (int j = 0; j < x.length; j++) System.out.print(Math.floor(x[j] / y[i]) + " "); System.out.println(); >

Int — Dividing two integers to a double in java, 3. Actaully w [L]/v [L] here both are integers. On the division operation it lost precision and truncated to integer value. Then the truncated …

Divide object of type Integer and Double

I want to divide a number by 100 and number is of Object type.

Object a = 33; Object b = .33; Double d = (Double) a / 100; Double e = (Double) b / 100; 

First, I had type cast to Double, but it’s failing «Cannot cast numeric value to java.lang.Double» for Integer.

Do I need to check instance before dividing? I am new and not sure what is correct way to do it?

EDIT: I cannot avoid Object

If you must use objects (and I suggest you don’t for a number of reasons) you could do this

Number a = 33; Number b = 0.33; Number d = a.doubleValue() / 100.0; Number e = b.doubleValue() / 100.0; 

However, you should really only use objects for numbers if

  • the value could be null
  • you are using it as a generic type e.g. List
  • you are using a type which doesn’t have a primitive e.g. BigDecimal

You need to use doubles not Objects

 final int a = 33; final double b = 0.33; final double d = a / 100.0; final Double e = b / 100.0; 

In Java you can cast primitives like int to a double but you can’t do the same with the wrapper classes like Integer and Double .

In your example, 33 is autoboxed to an Integer, which cannot then be cast to a Double. In the specific case you can avoid the exception by the following way:

 Object a = 33; if(a instanceof Number) < Double d = ((Number) a).doubleValue() / 100; System.out.println(d); >

But there is not the best way to solve you problem. Better to use primitive int and double, or theirs wrappers Integer and Double, but not Object.

Java — Is double division equal to integer division if there, Add a comment. 3. Yes, if x and y are both in the int range, unless the division is -2147483648.0 / -1.0. In that case, the double result will match the …

How to divide two ints and return a double in Java [duplicate]

I’m new to Android and I’m having trouble with a maths app I am creating.

The basic premise is to present the user with 2 numbers between 0 and 20 (questionTextView) then show the user a grid containing 3 incorrect answers and 1 correct answer. The user then clicks on the correct answer.

The issue I’m having is that the correct answer is not displaying to 2 decimal points.

I don’t understand why the correct answer is not displaying properly as I have cast both ints to doubles and included decimal formatting.

I’ve tried Math.round(), but I couldn’t get this to work — perhaps due to the way I have generated the questions within a for loop.

Any assistance would be greatly appreciated.

private static DecimalFormat df2 = new DecimalFormat("#.##"); public void generateQuestion() < //Create 2 random numbers between 0 and 20. Random rand = new Random(); int a = rand.nextInt(21); int b = rand.nextInt(21); if (a==b)< b = rand.nextInt(21); >questionTextView.setText(Integer.toString(a) + " / " + Integer.toString(b)); /*Create a random number between 0 and 3 to determine the grid square of the correct answer */ locationOfCorrectAnswer = rand.nextInt(4); //Calculate the correct answer. double correctAnswer = (int)(((double)a/(double)b)); //Generate an incorrect answer in case the correct answer is randomly generated. double inCorrectAnswer; /*Loop through each square and assign either the correct answer or a randomly generated number. */ for (int i=0; i else < inCorrectAnswer = 0.05 + rand.nextDouble() *20.0; while (inCorrectAnswer == correctAnswer)< inCorrectAnswer = 0.05 + rand.nextDouble() *20.0; >answers.add(df2.format(inCorrectAnswer).toString()); > > //Assign an answer to each of the buttons. button0.setText((answers.get(0))); button1.setText((answers.get(1))); button2.setText((answers.get(2))); button3.setText((answers.get(3))); 
double correctAnswer = (double)a/b; 
double correctAnswer = a/(double)b; 

Источник

Java – int and double divided by double java

When dividing an int by double doesn’t java first cast the int as a double then do the division – if so the two code blocks should effectively print the same value?

There seems to be some IEEE 754 floating point precision specifications I’m missing and/or jvm optimizations that inlines

 double i = 2.3 * 100000.0; double d = i / 100000.0; 

as
double d = 2.3 * 100000.0 / 100000.0;
effectively cancelling out the division and making this a no-op.

Best Solution

2.3 is not exactly representable in IEEE-754 64-bit binary floating-point. What happens in your first code sequence is:

  • The source text 2.3 is converted to the nearest representable value, 2.29999999999999982236431605997495353221893310546875.
  • The exact mathematical result of multiplying that by 100000 is not exactly representable either, so it is rounded to 229999.99999999997089616954326629638671875.
  • When this is converted to an int , the conversion truncates, producing 229999.
  • Dividing that by 100000 rounds again, producing 2.29999000000000020094148567295633256435394287109375.
  • When the above is printed, Java displays it as “2.29999”.
Java – What are the differences between a HashMap and a Hashtable in Java

There are several differences between HashMap and Hashtable in Java:

  1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
  2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
  3. One of HashMap’s subclasses is LinkedHashMap , so in the event that you’d want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap . This wouldn’t be as easy if you were using Hashtable .

Since synchronization is not an issue for you, I’d recommend HashMap . If synchronization becomes an issue, you may also look at ConcurrentHashMap .

Java – Is Java “pass-by-reference” or “pass-by-value”

Java is always pass-by-value. Unfortunately, when we deal with objects we are really dealing with object-handles called references which are passed-by-value as well. This terminology and semantics easily confuse many beginners.

public static void main(String[] args) < Dog aDog = new Dog("Max"); Dog oldDog = aDog; // we pass the object to foo foo(aDog); // aDog variable is still pointing to the "Max" dog when foo(. ) returns aDog.getName().equals("Max"); // true aDog.getName().equals("Fifi"); // false aDog == oldDog; // true >public static void foo(Dog d) < d.getName().equals("Max"); // true // change d inside of foo() to point to a new Dog instance "Fifi" d = new Dog("Fifi"); d.getName().equals("Fifi"); // true >

In the example above aDog.getName() will still return «Max» . The value aDog within main is not changed in the function foo with the Dog «Fifi» as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return «Fifi» after the call to foo .

public static void main(String[] args) < Dog aDog = new Dog("Max"); Dog oldDog = aDog; foo(aDog); // when foo(. ) returns, the name of the dog has been changed to "Fifi" aDog.getName().equals("Fifi"); // true // but it is still the same dog: aDog == oldDog; // true >public static void foo(Dog d) < d.getName().equals("Max"); // true // this changes the name of d to be "Fifi" d.setName("Fifi"); >

In the above example, Fifi is the dog’s name after call to foo(aDog) because the object’s name was set inside of foo(. ) . Any operations that foo performs on d are such that, for all practical purposes, they are performed on aDog , but it is not possible to change the value of the variable aDog itself.

For more information on pass by reference and pass by value, consult the following SO answer: https://stackoverflow.com/a/430958/6005228. This explains more thoroughly the semantics and history behind the two and also explains why Java and many other modern languages appear to do both in certain cases.

Related Question

Источник

Оцените статью