This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 5 years ago.
import java.util.Scanner;
public class test {
private static int number1 = 100;
private static int number2 = 1;
public static double avgAge() {
return (number1 + number2) / 2;
}
public static void main(String[] args) {
System.out.println("Average number: " + test.avgAge());
}
}
Why does test.avgAge() = 50.0 instead of 50.5? Is there a way to output 50.5 instead?
The calculation is done as an integer calculation.
If you replace 2 by 2.0 you will get 50.5. I recommend adding a comment to that line to explain this to future readers.
Alternatively you can explicitly cast to a double:
((double) (number1 + number2)) / 2
Just replace this function
import java.util.Scanner;
public class test {
private static int number1 = 100;
private static int number2 = 1;
public static double avgAge() {
return (number1 + number2) / 2.0;
}
public static void main(String[] args) {
System.out.println("Average number: " + test.avgAge()); //Average number: 50.5
}
}
It's because you're using ints through out the calculation before returning it as a double. Do the following:
private static double number1 = 100.0;
private static double number2 = 1.0;
Change these to double. Also, change the 2 to 2.0:
return (number1 + number2) / 2.0;
Read more about ints and doubles here:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
That's because of type promotion.
If in an operation, any of the operands is a double, then the result is promoted to double.
Since here all operands are ints, the division results in an int.
Type Promotion
return ((double)(number1 + number2)) / 2;
Related
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 1 year ago.
My task is to compare two numbers and return true if they are equal by three decimal places. When I print out the value of diff it is 0.0001, but it still doesn't enter the if(diff <= 0.0001) block.
public class DecimalComparator {
public static boolean areEqualByThreeDecimalPlaces(double num1, double num2) {
double diff = Math.abs(num1 - num2);
System.out.printf("%f", diff);
if(diff <= 0.0001) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
boolean test = areEqualByThreeDecimalPlaces(3.1756, 3.1755);
System.out.println(test);
test = areEqualByThreeDecimalPlaces(3.176, 3.175);
System.out.println(test);
}
}
When you need arbitrary precision use BigDecimal. Also, your magic number should be 0.001 for three decimal places. Like,
public static boolean areEqualByThreeDecimalPlaces(double num1, double num2) {
return new BigDecimal(num1).subtract(new BigDecimal(num2)).abs()
.compareTo(new BigDecimal(0.001)) <= 0;
}
public static void main(String[] args) {
System.out.println(areEqualByThreeDecimalPlaces(3.1756, 3.1755));
System.out.println(areEqualByThreeDecimalPlaces(3.176, 3.175));
}
Outputs
true
false
While I believe #Elliot Frisch has the best Java approach, it is always difficult to know if one should introduce concepts beyond the standard primitives for what appears to be homework.
In the alternative, knowing that the desired value is 3 decimal places, the problem may be re-conceptualized by multiplying by 1000 and using an int.
Example:
public static boolean areEqualByThreeDecimalPlaces(double num1, double num2) {
final int mult = 1000;
int i1 = (int)(num1 * mult);
int i2 = (int)(num2 * mult);
return (Math.abs(i1 - i2)) == 0;
}
The output shows the expected true and false for the test cases.
Just an alternative approach to consider if one cannot switch to using other Java classes.
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 2 years ago.
I have the following method in a Java program:
public void Div(int a, int b){
//exception in order to check if the second argument is 0
try{
int div1 = (a / b);
double div = div1;
System.out.println("The division of the two numbers is: " + div);
}
catch(ArithmeticException e){
System.out.println("You can't divide a number by 0");
}
This only works if numerator is larger than the denominator ( e.g 8/2). If the numerator is smaller than the denominator I get a result of 0.0 (e.g. 2/8).
What can I do to make it work?
It's happening because of integer division. You can cast one of the arguments to double and store the result to a double variable to fix the issue.
public class Main {
public static void main(String[] args) {
div(5, 10);
}
public static void div(int a, int b) {
try {
double div = (double) a / b;
System.out.println("The division of the two numbers is: " + div);
} catch (ArithmeticException e) {
System.out.println("You can't divide a number by 0");
}
}
}
Output:
The division of the two numbers is: 0.5
On a side note, you should follow Java naming conventions e.g. the method name, Div should be div as per the Java naming conventions.
(a/b) You're doing integer division. You need to typecast to other data types that can store decimal like double.
double div = (double) a / b;
This question already has answers here:
Sum of the digits of the number 2^1000 [closed]
(11 answers)
Closed 3 years ago.
import java.math.*;
public class PowerDigitSum {
public static void main(String[] args) {
double[] digits ;
digits = new double[302];
double i = Math.pow(2, 1000);
double c = 301;
double c1 = 0;
double d = 0;
while(c>=0) {
c1 = Math.pow(10, c);
d = Math.floor(i/c1);
i = i - d*c1;
digits[(int)c] = (int)d;
c = c-1;
}
double sum = 0;
c = 0;
while (c<302) {
sum = sum+digits[(int)c];
c= c+1;
}
System.out.println(sum);
}
}
The output is 1281 but that's not correct according to projecteuler. What am I doing wrong?
You can't do correct math with double values that large due to their limited nature.
You could probably fix your code with BigDecimal, but it is much easier using BigInteger. Hint: it has a pow method, and you can work out the digit sum starting from toString.
Is there an exponential operator in Java?
For example, if a user is prompted to enter two numbers and they enter 3 and 2, the correct answer would be 9.
import java.util.Scanner;
public class Exponentiation {
public static double powerOf (double p) {
double pCubed;
pCubed = p*p;
return (pCubed);
}
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
double num = 2.0;
double cube;
System.out.print ("Please put two numbers: ");
num = in.nextInt();
cube = powerOf(num);
System.out.println (cube);
}
}
There is no operator, but there is a method.
Math.pow(2, 3) // 8.0
Math.pow(3, 2) // 9.0
FYI, a common mistake is to assume 2 ^ 3 is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.
To do this with user input:
public static void getPow(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter first integer: "); // 3
int first = sc.nextInt();
System.out.println("Enter second integer: "); // 2
int second = sc.nextInt();
System.out.println(first + " to the power of " + second + " is " +
(int) Math.pow(first, second)); // outputs 9
The easiest way is to use Math library.
Use Math.pow(a, b) and the result will be a^b
If you want to do it yourself, you have to use for-loop
// Works only for b >= 1
public static double myPow(double a, int b){
double res =1;
for (int i = 0; i < b; i++) {
res *= a;
}
return res;
}
Using:
double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);
There is the Math.pow(double a, double b) method. Note that it returns a double, you will have to cast it to an int like (int)Math.pow(double a, double b).
you can use the pow method from the Math class. The following code will output 2 raised to 3 (8)
System.out.println(Math.pow(2, 3));
In case if anyone wants to create there own exponential function using recursion, below is for your reference.
public static double power(double value, double p) {
if (p <= 0)
return 1;
return value * power(value, p - 1);
}
This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 9 years ago.
My code:
public class Test {
public static int l = 29;
public static int w = 16;
public static int total = w + l;
public static int result = w / total;
public static int Result = total * 100;
public static void main(String[] args) {
System.out.println("You're W/L ratio is: " + (Result) + "%"); // Display the string.
}
}
Response in console: You're W/L ratio is: 0%
You're doing int division which always returns an int and so w / total will always be 0 since total is always greater than w. Do the multiplication by 100 first.
int result = (w * 100) / total;
Also you will want to learn and use java naming rules. Variable names should begin with a lower case letter.
Do the calculation by casting w and total to double, or just make them double to begin with. For the first option:
public static double result = (double)w / (double)total;
whenever you do division when both numbers are integers, in result you will get integer in return.
which actually means you will get floor value of (a/b); ie:
1/2=0 as 1/2=> 0.5> floor of 0.5= 0;
3/4=0 as 3/4=> 0.75> floor of 0.75= 0;
etc