Am i properly handling this float variable? - java

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.

Related

How to store the result of some operations on Integer in to a different data type in java

So I have two Integers, I am finding their median by adding them and then dividing them by 2. I want to store their floating result. So I am doing -
float res = (float) (num1 + num2) / 2;
Sometimes this expression return 0.0 for non zero inputs. I think the problem is num1 and and num2 range can vary to the full spectrum of 32 bits. So when both are in the high spectrum, float cast breaks as its not able to store the results and returns 0.0.
I don't want to do (float)num1/2 + (float)num2/2 as I might loose decimal precision during this.
Any pointers on how can I handle this scenario.
Depending what your actual requirements are, float may not do the trick either.
For a correct result try this:
int num 1 = ...
int num 2 = ...
double avg = (((long) num1) + num2) / 2D;
The point is to add the int's as long's (cast one to long, the other is cast automatically because long + int causes a widening conversion). This avoids a possible integer overflow when the sum of both ints is larger than Integer.MAX_VALUE (or smaller than Integer.MIN_VALUE).
Then divide by two, by suffixing the 2 literal as double literal an explicit cast is not needed. Again for the division this causes an implicit widening conversion where long / double = double.
Use BigDecimal type for this purpose.
int num1 = 1;
int num2 = 2;
BigDecimal sum = new BigDecimal(num1 + num2);
BigDecimal result = sum.divide(new BigDecimal(2));
In case num1 and num2 are the floating-point types, use
BigDecimal sum = new BigDecimal(num1).add(new BigDecimal(num2));
Then you can get any type from result, for example
double v = result.doubleValue();
I did a simple test, and as I mentioned in my comment, you can cast it with double or long (as another option):
public class Casting {
public static void main(String[] args) {
// the maximum positive value for a signed binary integer
int num1 = Integer.MAX_VALUE;
int num2 = Integer.MAX_VALUE;
float resFloat = ((float)num1 + num2) / 2;
double resDouble = ((double)num1 + num2) / 2;
double resLong = ((long)num1 + num2) / 2;
// Testing [Expected Result is 2147483647]
System.out.println("Size: " + Integer.SIZE); // in bits (on my machine)
System.out.println("Max Value: " + Integer.MAX_VALUE);
System.out.printf("Float Cast: %f\n", resFloat);
System.out.printf("Double Cast: %f\n", resDouble);
System.out.printf("Long Cast: %f\n", resLong);
}
}
Output
Size: 32
Max Value: 2147483647
Float Cast: 2147483648.000000
Double Cast: 2147483647.000000
Long Cast: 2147483647.000000

Dividing numbers [duplicate]

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

How do I force a number with unknown digits behind the decimal mark? [duplicate]

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

Syntax error on tokens in string text

I keep getting "syntax error on tokens please delete these tokens" on pretty much all of my System.out.println text after the first instance of System.out.println. I don't know what this means or how to fix it? I'm a very new beginning so there might be multiple mistakes in this code. I'm also getting "Syntax error on token ""doubled is"", invalid AssignmentOperator" and """squared is"", invalid AssignmentOperator" errors as well. This is an assignment for a class with the end result supposed to be
the opposite of n is y
n doubled is y
one-half of n is y
n squared is y
the reciprocal of n is y
one-tenth of n is y and y squared is z
n minus the last digit of n is y
the sum of n and n+1 and n+2 is y
Thank you!
import java.util.Scanner;
public class Arithmetic {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = scanner.nextInt();
int opposite = n*-1;
System.out.println("The opposite of" n "is" opposite);
int twoTimes = n*2;
System.out.println(n "doubled is" twoTimes);
int half = n/2;
System.out.println("half of "n "is" half);
int square= n*n;
System.out.println(n "squared is" square);
int reciprocal= 1/n;
System.out.println("the reciprocal of" n "is" reciprocal);
double fraction = n*.10;
double fractionTwo = fraction*fraction;
System.out.println("one-tenth of" n "is" fraction "and" fraction "squared is" fractionTwo);
// int lastDigit =
// System.out.println();
int sum= n+1;
int sumTwo= n+2;
int sumTotal= sum + sumTwo;
System.out.println("the sum of" n "and" sum "and" sumTwo "is" sumTotal);
}
}
**also if anybody would like to help me figure out the "n+1"/"n+2" formula and how to format that in code that would be appreciated!
There's a few mistakes with this code.
You're not concatenating correctly on any of your print to consoles.
System.out.println("The opposite of" n "is" opposite);
should be:
System.out.println("The opposite of" + n + "is" + opposite);
When we want to combine Strings we use the + sign.
int reciprocal= 1/n; will not work;
it should be double reciprocal= 1.0/n; assuming that n is an int.
"n+1"/"n+2" would simply be: double result = (n + 1.0) / (n + 2.0); assuming that n is an int.
That's not how you concatenate (link) two strings!
This code, and other similar ones,
System.out.println(n "doubled is" twoTimes);
are wrong.
I think you want to link n, "doubled is" and twoTimes together, right?
Right now you are linking them with spaces. But space characters in Java doesn't concatenate strings. So that's why the compiler complained.
In Java, + is both used to do addition and concatenation of strings! So you should change the above to:
System.out.println(n + "doubled is" + twoTimes);
But wait! Where have your spaces gone? This is because + doesn't automatically adds a space for you, you need to add it yourself.
System.out.println(n + " doubled is " + twoTimes);
Alternatively, you can use String.format to format your string. This
/* Explanation: n will be "inserted" to the first %d and twoTimes will
be inserted to the second %d. And %d basically means "express the thing in
decimal"*/
String.format("%d doubled is %d", n, twoTimes)
is the same as
n + " doubled is " + twoTimes
Regarding your formula question:
In Java, there are two different number types, int and double. (There are actually a lot more, but they're irrelevant) int and double do different things when they are divided. And they have different literals.
5 is an int literal, 5.0 is a double literal. See? Numbers without decimal places are ints and those with decimal places are called doubles.
So what's wrong with your formula? Let's first take a look at what the is the result of dividing int and double
int / int: 1 / 5 = 0
int / double: 1 / 5.0 = 0.2
double / int: 1.0 / 5 = 0.2
double / double: 1.0 / 5.0 = 0.2
int / 0: 1 / 0 = Exception!
double / 0: 1.0 / 0 = NaN
In your code:
int reciprocal= 1/n;
and other similar lines, you are doing division of int. So that's why the above code doesn't work. What you should do is change one of the numbers to a double! And also change the type to double.
double reciprocal = 1.0 / n;
------ ---
changes here as well!

Can val be used as variable in Java?

Is the program legal or not?
I am trying to correct out a statement that will print the value of 3 divided by 2.
I know this isn't correct.
System.out.print("The result is" + 3 / 2 + ".")
This is my answer.
System.out.print("The result is" + val + ".")
double val = 3 / 2
Is my answer correct or no? If not, how would I call upon the number?
You can do the following
double val = 3.0 / 2;
System.out.print("The result is" + val + ".");
the value val must be declared before it is printed. Also you need to make one of the number of type double so when the division is done, the answer is a double also. Else you lose precision.
the following is also valid:
double val = 3 / 2.0;
System.out.print("The result is" + val + ".");
if you do double val = 3 / 2; then 3/2 division is made with two integers which also give another integer. So 3/2 should give 1.5 but since we are only diving integers, it will omit the .5 and only give 1. Then 1 is casted as a double and becomes 1.0.
What you have is mostly correct:
float val1 = 3;
float val2 = 2;
float val= val1/val2;
System.out.println("The result is " + val + ".");
Remember your semicolons.
Also... You are correct to use a double (or float). Because otherwise your answer will be truncated.
EDIT:
Actually... I come to find that trying to do the operation in one shot still truncates the answer. It isn't correct unless both the values are set as floats. Then, run the math.
Here is proof: online java compiler
You need to declare first the variables. And if you want fraction numbers you need to do that with them. Need " ; " at the end of every statement. If you try it out in eclipse it will sign error to you when you don't write it where it need to be.
float num1 = 3;
float num2 = 2;
float val = num1 / num2;
System.out.print("The result is" + val + ".");
// Another way:
double num1 = 3;
double num2 = 2;
double val = num1 / num2;
System.out.print("The result is" + val + ".");
This should work:
double val = 3.0 / 2;
System.out.print("The result is" + val + ".");
Edit:
This is a case of integer division. When division is performed between two integers (here 3 and 2), the output is an integer and the fractional part gets trimmed off. So,3/2 will yield 1 which since you assign to a double variable, becomes 1.0.
When I do 3.0/2, 3.0 is a double value. The output here is a double value too i.e. 1.5; the fractional part is retained. Hence, my solution works.

Categories

Resources