Math equation result loses decimals when displayed - java

I am writing a program for class which will allow the user to calculate the area of an isosceles trapezoid. Here is my code:
import java.util.Scanner;
import java.lang.Math;
public class CSCD210Lab2
{
public static void main (String [] args)
{
Scanner mathInput = new Scanner(System.in);
//declare variables
int topLength, bottomLength, height;
//Get user input
System.out.print("Please enter length of the top of isosceles trapezoid: ") ;
topLength = mathInput.nextInt() ;
mathInput.nextLine() ;
System.out.print("Please enter length of the bottom of isosceles trapezoid: ") ;
bottomLength = mathInput.nextInt() ;
mathInput.nextLine() ;
System.out.print("Please enter height of Isosceles trapezoid: ") ;
height = mathInput.nextInt() ;
mathInput.nextLine() ;
double trapArea = ((topLength + bottomLength)/2*(height));
System.out.println();
System.out.printf("The area of the isosceles trapezoid is: "+trapArea);
}
}
If I enter say, 2 for topLength, 7 for bottomLength, and 3 for height, I will get an answer of 12.0, when it should result in an answer of 13.5. Does anyone know why my code is printing out wrong answers and not printing the .5?

The base of the issue can be known as "Integer Division". In Java, dividing 2 integers will yield a non-rounded integer.
Below are multiple ways to fix the issue you are having. I prefer the first method as it allows you to use your formula with non-integer values. Not all the lengths of a triangle are integers :)
Using the Scanner#getDouble and placing topLength, bottomLength, and height in doubles will give you the desired output.
Your code will then look like this :
public static void main(String[] args) {
Scanner mathInput = new Scanner(System.in);
// declare variables
double topLength, bottomLength, height;
// Get user input
System.out.print("Please enter length of the top of isosceles trapezoid: ");
topLength = mathInput.nextDouble();
mathInput.nextLine();
System.out.print("Please enter length of the bottom of isosceles trapezoid: ");
bottomLength = mathInput.nextDouble();
mathInput.nextLine();
System.out.print("Please enter height of Isosceles trapezoid: ");
height = mathInput.nextDouble();
mathInput.nextLine();
double trapArea = ((topLength + bottomLength) / 2 * (height));
System.out.println();
System.out.printf("The area of the isosceles trapezoid is: " + trapArea);
}
You could also cast your ints to doubles and calculate your trapArea as so :
double trapArea = (((double)topLength + (double)bottomLength) / 2 * ((double)height));
OR even simple, if you want, convert the 2 you are deviding to a double :
double trapArea = ((topLength + bottomLength) / 2.0 * (height));
All of these options will yield :
The area of the isosceles trapezoid is: 13.5

Related

Possible method to shorten extremely large numbers?

This is the value of the double "m" in my program (the mass of a planet after calculations, this value is specifically for the mass of Earth)
5.973405437304745E24
When printing using System.out.println(m);
The output is
5.973405437304745E24 (correct output)
When printing using System.out.println(Math.round(m));
The output is
9223372036854775807 (incorrect output)
How am I able to shorten the value of m so it fits within %6s?
Like this for example
5.97E24
This is my code below. The assignment requires us to output the final values in a formatted chart (as I've attempted to do below)
//Java imports
import java.util.*;
import java.lang.Math;
//Main class
class Main {
public static void main(String[] args) {
//Initializing scanner name userInput
Scanner userInput = new Scanner (System.in);
//Greeting statement, prompts user to input the circumference in km
System.out.println("\nWelcome to the Escape Velocity Application. To begin, please enter the following information below. \nEnter the circumference (km):");
//Stores circumference in double named "circum" and converts the value to its meter equivalent (unit conversion required)
double circum = userInput.nextDouble() * Math.pow(10, 3);
//Prompts user to input the acceleration in m/s^2
System.out.println("Enter the acceleration due to gravity (m/s^2):");
//Stored value in double named "f"
double f = userInput.nextDouble();
//Gravitational Constant
double G = 6.67408e-11;
//1 - Radius calculation using the circumference of a circle formula
double r = circum/(2*Math.PI);
//2 - Mass calculation using the gravity formula
double m = f*Math.pow(r, 2)/G;
//3 - Calculation escape velocity using the escape velocity formula
double e = (Math.sqrt((2.0*G*(m))/r));
//Final output statements
System.out.println("\nThe radius is: " + Math.round(r * Math.pow(10, -3)) + " kilometers.");
System.out.println("The mass is: " + m + " kg.");
System.out.println("The escape velocity is: " + Math.round(e) + " m/s.");
//Formatted output statements
System.out.format("\n%20s %6s %10s", "Radius:", Math.round(r * Math.pow(10, -3)), "km.");
System.out.format("\n%20s %6s %10s", "Mass:", Math.round(m), "kg.");
System.out.format("\n%20s %6s %10s", "Escape Velocity:", Math.round(e), "m/s.");
}
}
This is what the output looks like. The center of the second line is offset due to the long value of m.
The radius is: 6378 kilometers.
The mass is: 5.973405437304745E24 kg.
The escape velocity is: 11181 m/s.
Radius: 6378 km.
Mass: 9223372036854775807 kg.
Escape Velocity: 11181 m/s.
You could use the following code:
double x = 5.973405437304745e24;
System.out.printf("Mass: %.2e kg.%n", x);
Which outputs Mass: 5.97e+24 kg..
%.2e formats the number and %n just adds a newline character. The .2 specifies that two decimal places after the dot are desired. The e requests scientific notation from the formatter.
The problem with Math.round() is, that the result is stored in a long which cannot represent such a large number.

Hypotenuse program, can't figure out how to let program run until user enters 2

I am writing a program that finds the hypotenuse of a triangle, I need to let the program run an arbitrary amount of times until the user enters 2. I cannot figure out how to end the program when the user enters 2.
package assignment5a;
import java.util.Scanner;//import Scanner
public class Assignment5A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);//new Scanner variable
int answer;
double side1, side2, result;
System.out.println("Enter 1 to calculate the hypotenuse of a triangle or enter 2 to quit.");
answer = sc.nextInt();
while(answer < 0 || answer > 2){
System.err.println("Please enter a valid answer.");
System.out.println("Enter 1 to calculate the hypotenuse of a triangle or enter 2 to quit.");
answer = sc.nextInt();
}
System.out.println("Enter side 1 of the triangle :");//input for side 1
side1 = sc.nextDouble();
System.out.println("Enter side 2 of the triangle :");//input for side 2
side2 = sc.nextDouble();
result = hypotenuse(side1, side2);//declares result as the result of the method hypotenuse
System.out.printf("Hypotenuse of your triangle is: %.2f%n", result);//prints results
}
public static double hypotenuse(double s1, double s2){//method for calculating hypotenuse
double hypot;
hypot = Math.sqrt((Math.pow(s1, 2) + Math.pow(s2, 2)));
return hypot;
}
}
Wilmol's answer and Elliot Frisch's answer / comment are half the solution.
The other half is that you need an outer loop around most of the logic so it'll repeat. Put most of main() inside a loop that uses while (true) { to start so that it'll loop forever.
Then use the logic of if (answer == 2) { ... to actually break out when the user inputs 2.
Few options:
if (answer == 2)
{
break;
}
if (answer == 2)
{
return;
}
if (answer == 2)
{
System.exit(0);
}
So I figured it out. Your answers helped a lot but i ended up putting two while loops. The code is below:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);//new Scanner variable
int answer;
double side1, side2, result;
System.out.println("Enter 1 to calculate the hypotenuse of a triangle or enter 2 to quit.");
answer = sc.nextInt();
while(answer < 0 || answer > 2){
System.err.println("Please enter a valid answer.");
System.out.println("Enter 1 to calculate the hypotenuse of a triangle or enter 2 to quit.");
answer = sc.nextInt();
}
while(answer == 1){
System.out.println("Enter side 1 of the triangle :");//input for side 1
side1 = sc.nextDouble();
System.out.println("Enter side 2 of the triangle :");//input for side 2
side2 = sc.nextDouble();
result = hypotenuse(side1, side2);//declares result as the result of the method hypotenuse
System.out.printf("Hypotenuse of your triangle is: %.2f%n", result);//prints results
System.out.println("Enter 1 to calculate the hypotenuse of a triangle or enter 2 to quit.");
answer = sc.nextInt();
}
}
public static double hypotenuse(double s1, double s2){//method for calculating hypotenuse
double hypot;
hypot = Math.sqrt((Math.pow(s1, 2) + Math.pow(s2, 2)));
return hypot;
}
}

"Write a Java program to compute the area of a polygon." - getting a different solution than www.w3resource.com

Here's the exercise:
35. Write a Java program to compute the area of a polygon. Go to the editor
Area of a polygon = (n*s^2)/(4*tan(π/n))
where n is n-sided polygon and s is the length of a side
Input Data:
Input the number of sides on the polygon: 7
Input the length of one of the sides: 6
Expected Output
The area is: 130.82084798405722
My code returns 127.30573435631248 (length = 7, sides = 6)
The code on the website returns 130.82084798405722 (length = 7, sides = 6)
I'm having trouble seeing why mine is different from theirs...
Any ideas?
Here's my code:
public static void exercise35(){
int number1 = integerInput(); //set to 7, length
int sides = integerInput(); //set to 6, sides
double area = (sides * (number1 * number1)) / (4.0 * Math.tan((Math.PI / sides)));
System.out.println("The area of a polygon with " + sides + " sides of length " + number1 + " = " + area);
}
Here's the solution from http://www.w3resource.com/java-exercises/basic/index.php (exercise #35)
import java.util.Scanner;
public class Exercise35 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Input the number of sides on the polygon: ");
int ns = input.nextInt();
System.out.print("Input the length of one of the sides: ");
double side = input.nextDouble();
System.out.print("The area is: " + polygonArea(ns, side)+"\n");
}
public static double polygonArea(int ns, double side) {
return (ns * (side * side)) / (4.0 * Math.tan((Math.PI / ns)));
}
}
You mixed sides and number in the formula.
That teaches an interesting lesson of programming: "Give sensible names to variables".
Change 6 and 7 and you'll get the answer you want : ) And in the future, please try debugging your code first to see what's going on.

I need to use double instead of int for my outcome to be correct. Why? (Java)

Today i tried to make a simple program in Java that gives me the average of the numbers i entered.
The problem is that if i use int added (as shown below), i don't get the same answer as when i use double added.
Code:
public class Main {
public static void main(String[] args) {
int amount;
int number;
int added = 0;
double average;
Scanner input = new Scanner(System.in);
System.out.println("This program calculates the average of the numbers entered by you.");
System.out.println("How many numbers do you want to enter?");
amount = input.nextInt();
for(int i=1; i<=amount; i++){
System.out.println("Enter a number:");
number = input.nextInt();
added = added + number;
}
average = added/amount;
System.out.println("The average of the numbers entered is: " + average);
}
}
Result:
This program calculates the average of the numbers entered by you.
How many numbers do you want to enter?
6
Enter a number:
3
Enter a number:
2
Enter a number:
4
Enter a number:
1
Enter a number:
6
Enter a number:
5
The average of the numbers entered is: 3.0
When i use double, i get the right answer:
public class Main {
public static void main(String[] args) {
int amount;
int number;
double added = 0;
double average;
Scanner input = new Scanner(System.in);
System.out.println("This program calculates the average of the numbers entered by you.");
System.out.println("How many numbers do you want to enter?");
amount = input.nextInt();
for(int i=1; i<=amount; i++){
System.out.println("Enter a number:");
number = input.nextInt();
added = added + number;
}
average = added/amount;
System.out.println("The average of the numbers entered is: " + average);
}
}
Result when i use double added instead of int added:
This program calculates the average of the numbers entered by you.
How many numbers do you want to enter?
6
Enter a number:
3
Enter a number:
2
Enter a number:
4
Enter a number:
1
Enter a number:
6
Enter a number:
5
The average of the numbers entered is: 3.5
Why does this happen and what should i do to avoid it?
To me it seems like added could be an int because i don't add up decimals but i add up whole numbers.
Thank you in advance.
In order for added/amount to return a non integer, either added or amount must be float or double or cast to either of them.
When both are int, an integer division takes place and the result is only converted to double after the division in order to be stored in your double average variable.
The result of a division in which both elements are integer, will be an integer. At least one of them needs to be a float or a double for the result of the division to be a floating point number.

Why won't my sine method work

I'm a beginner programmer and new to stackoverflow.
So i have been making a Math Formula Solver and I have 4 formulas up and functioning. I am working on my Sine formula solver and it won't work. I use a scanner and switch to select the formula and input the variables. Here is what i have.
Scanner input = new Scanner(System.in);
System.out.println("Enter '0' for list of formula call numbers");
System.out.print("Enter the formula request number: " );
int mFormula = input.nextInt();
switch(mFormula)
{
case 5 :
System.out.println("Sine Problem Solver, please enter your variables below: ");
System.out.println();
System.out.print("Value for known side: ");
int x = input.nextInt();
System.out.println();
System.out.print("Value for degrees: ");
int x3 = input.nextInt();
System.out.println();
double Sine = (x * Math.sin(x3));
System.out.print("The side length is: " + Sine);break;
}
im just really confused on why it isn't working.
It seems that your main problem is that Math.sin doesn't take degrees but radians. Try
Math.sin(Math.toRadians(x3))

Categories

Resources