How to get the actual average, not rounded? - java

this is what I have (changed the print message for this question), and when I do 4 and 11, you should get 7.5, but it's only giving me 7. how do I fix this?
import java.util.Scanner;
class U1_L6_Average_Finder {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a;
int b;
System.out.println("put in 4");
a = scan.nextInt();
System.out.println("Put in 11");
b = scan.nextInt();
System.out.println("Here is your average");
System.out.print((a + b) / 2);
}

You could coerce the quotient to a floating-point value by changing the 2 (denominator) to a 2.0, 2f, 2.0f. If you want a double, you can use a d instead of an f.
public class AverageFloatingPointCoercionExample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a, b;
System.out.print("Enter value #1 (4): ");
a = scan.nextInt();
System.out.print("Enter value #2 (11): ");
b = scan.nextInt();
System.out.print("Here is your average: ");
System.out.print((a + b) / 2.0f); // 7.5
}
}
Alternatively, you can cast the numerator explicitly.
System.out.print(((float) (a + b)) / 2);

You're using integers (int a, b;), so it will round your results.
Instead of it, use double or float to get what you want, e.g:
double a, b;
But, if you don't want to modify the type of your variable, you can edit your last System.out.print using f (for example), that will convert your value to float, e.g:
System.out.print((a + b) / 2.0f);
Check this to understand more about variables:
Java Variables

You have the input/averaging nailed. So here's the missing bit.
Just output r...
But if you want a certain number of decimal places (5 here)...
I did this in case you wanted to average more than 2 items...
import java.text.DecimalFormat;
class Playground {
public static void main(String[ ] args) {
int i = 5;
int j = 17;
double r = (double)i/j;
DecimalFormat df = new DecimalFormat("#.#####");
System.out.println(r);
System.out.println(df.format(r));
}
}
Outputs:
0.29411764705882354
0.29412

You are using integer divison. Integer divison will result integer as answer. You have to change one of the values to double.
Example:
System.out.println((double)(a+b)/2);
or
System.out.println((a+b)/2.0));

Related

how to convert decimal value in to a Fraction value?

excepted output : 1/4,1/2,3/4,1,5/4,3/2
but my output is coming as in the decimal form . Please help how to print in the form of fraction only.
import java.util.*;
public class Hello {
public static void main(String[] args) {
//Your Code Here
Scanner s=new Scanner(System.in);
int n=s.nextInt();
double d=1/4.0,sum=0;
for(int i=0;i<n;i++) {
sum+=d;
System.out.print(sum+" ");
}
}}
take input in form of string so it will take input in required format and split it by "/" i.e someString.spit("/").
after that make one for loop and take two number and in two different variable store it.
and then take division for both and print it by using "/" in between them.
public class NewClass {
public static void main(String[] args) {
System.out.println(convertype(0.75));
}
public static String convertype(double decimal){
int digitsAfterPoint = String.valueOf(decimal).length() - String.valueOf(decimal).indexOf('.')+1; // get the count of digits after the point // for example 0.75 has two digits
BigInteger numerator = BigInteger.valueOf((long)(decimal*Math.pow(10, digitsAfterPoint))); // multiply 0.75 with 10^2 to get 75
BigInteger denominator = BigInteger.valueOf((long)(Math.pow(10, digitsAfterPoint))); // 10^2 is your denominator
int gcd = numerator.gcd(denominator).intValue(); // calculate the greatest common divisor of numerator and denominator
if (gcd > 1 ){ // gcd(75,100) = 25
return String.valueOf(numerator.intValue()/gcd) +" / " + String.valueOf(denominator.intValue()/gcd); // return 75/25 / 100/25 = 3/4
}
else{
return String.valueOf(numerator) +" / " + String.valueOf(denominator); // if gcd = 1 which means nothing to simplify just return numerator / denominator
}
}
}
Wrote a method where you can convert double numbers to fraction. Use this to convert it and print as below,
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
double d=1/4.0,sum=0;
for(int i=0;i<n;i++) {
sum+=d;
System.out.print(toFraction(sum)+" ");
}
}
static String toFraction(double x) {
int w = (int) x;
int n = (int) (x * 64) % 64;
int a = n & -n;
return n == 0 ? w+"" : (w * (64 / a) + (n / a)) + "/" + 64 / a;
}
}

Coding a Math Equation

So I'm trying to code this equation using java:
I'm taking a, b, and c from the user.
This is the code I have so far:
import java.util.Scanner;
class QaudraticFunction{
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println("Enter a: ");
double a = input.nextDouble();
System.out.println("Enter b: ");
double b = input.nextDouble();
System.out.println("Enter c: ");
double c = input.nextDouble();
double val1 = (Math.pow(b,2.0)) - (4.0*a*c);
double discriminant = Math.sqrt(val1);
double val2 = (-b)-(discriminant);
double r2 = val2/(2.0*a);
System.out.println("r2 = " + r2);
}
}
I think my issue is a logical error because the program compiles and runs correctly. When I enter the values for a, b and c. I get r2 = NaN
Two possible reasons you are seeing a NaN.
The denominator is 0. This is only possible if a is set to 0 or 0.0. I'm going to assume that's not the case.
The other possibility is that you are performing a square root of a negative number, which (in java) is a NaN. See Math.sqrt javadoc for more details.
If the argument is NaN or less than zero, then the result is NaN.

program to convert decimal numbers to another base does not work correctly

I wrote this program to convert decimal numbers to another bases but when I run it with eclipse the answer is 0 for any number.
import java.util.Scanner;
public class dtb {
public static void main(String[] args) {
Scanner myscanner = new Scanner (System.in);
int num= myscanner.nextInt();
int base= myscanner.nextInt();
int i=0;
int y=0;
while (num >= base){
int x = (num%base);
num = num/base;
y = (y + (x*(10^i)));
}
System.out.println (y) ;
}
}
The ^ operator doesn't do what you think. If you want to elevate to a power, use Math.pow():
Math.pow(10, i)
but since this method returns a double, you will have to cast it to int:
(int) Math.pow(10, i)
Check your input. you num value should be greater than base value. eg: 30,20 output is 100.

Does Java have an exponential operator?

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

quadratic formula with scanner inputs

Okay so I am a complete Java noob, and I'm trying to create a program for class that runs a quadratic equation using scanner inputs. So far what I've got is this:
import java.util.*;
public class QuadraticFormulaSCN {
public static void main(String[]args) {
System.out.println("insert value for a:");
Scanner scan1 = new Scanner(System.in);
double a = scan1.nextDouble();
System.out.println("insert value for b:");
Scanner scan2 = new Scanner(System.in);
double b = scan2.nextDouble();
System.out.println("insert value for C:");
Scanner scan3 = new Scanner(System.in);
double c = scan3.nextDouble();
double answer =((Math.sqrt(Math.pow(b,2)-(4*a*c))-b)/2);
double final2 =(-b + Math.sqrt(Math.pow(b,2)-(4*a*c)))/2;
System.out.println("The x values are:" + answer + final2);
}
}
But I get a weird output, specifically NaNaN... What do I do to fix this? What am I doing wrong?
I'm a little late to answer, but I corrected your problems (described in the other answers), fixed one of your calculations, and cleaned up your code.
import java.util.*;
public class Test {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Insert value for a: ");
double a = Double.parseDouble(s.nextLine());
System.out.println("Insert value for b: ");
double b = Double.parseDouble(s.nextLine());
System.out.println("Insert value for c: ");
double c = Double.parseDouble(s.nextLine());
s.close();
double answer1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
double answer2 = (-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
if (Double.isNaN(answer1) || Double.isNaN(answer2))
{
System.out.println("Answer contains imaginary numbers");
} else System.out.println("The values are: " + answer1 + ", " + answer2);
}
}
NaN is something you get when the calculation is invalid. Such as dividing by 0 or taking the squareroot of -1.
When I test your code with a = 1, b = 0 and c = -4 the answers is 2.02.0
The formatting is not right and the calculation of final2 is not negated.
Otherwise the code is right.
To improve you could check whether the discriminant is negative.
double d = b*b -4 * a * c;
if (d < 0){
System.out.println("Discriminant < 0, no real solutions" );
return;
}
double x1 = (-b -sqrt(d))/(2*a);
double x2 = (-b +sqrt(d))/(2*a);
System.out.format("The roots of your quadratic formula are %5.3f and %5.3f\n",x1,x2);
Or, if you prefer support for solutions from the complex domain:
if (d < 0) {
System.out.println("Discriminant < 0, only imaginary solutions");
double r = -b / (2 * a);
double i1 = -sqrt(-d) / (2 / a);
double i2 = sqrt(-d) / (2 / a);
System.out.format("The roots of your quadratic formula are (%5.3f + %5.3fi) and (%5.3f + %5.3fi)\n",r, i1, r, i2);
return;
}
You are getting NaN because you are attempting to take the square root of a negative number. In math that's not allowed unless you are allowing complex numbers, e.g. 1 +/- 2i.
This can happen in quadratic formulas when the discriminant (the thing in the square root) is negative, e.g. x^2 + 6*x + 100: b^2 - 4ac = 36 - 400 = -364. Taking the square root of a negative number in Java leads to NaN. (not a number)
To test for NaN, use Double.isNaN and handle the NaN appropriately.
In addition, your calculations are incorrect even if NaN isn't being encountered:
$ java QuadraticFormulaSCN
insert value for a:
1
insert value for b:
5
insert value for C:
6
The x values are:-2.0-2.0
This should have outputted 2.0 and 3.0
You should only do the calculation when
discriminant is equal or greater than zero
if(((Math.pow(b,2)-(4*a*c))>= 0){ /* Calculation here */ }
else {/*error message or complex number calculus*/};
One thing I always try to do is put all my math in appropriate parenthesis to avoid an, all too easy, Order of Operations mistake. The NaN is saying "Not a number." You would also get that message if the user input numbers that could not produce a result, such as a trying to get the square root of a negative number. Also, just as a note, you can save sometime by only using on Scanner for a,b, and c.
public class QuadraticFormula{
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
double quadPos = (-b + Math.sqrt(Math.pow(b,2)-(4*a*c)))/(2*a);
double quadNeg = (-b - Math.sqrt(Math.pow(b,2)-(4*a*c)))/(2*a);
System.out.println("-b - = " + quadNeg + "\n-b + = " + quadPos);
}
}

Categories