I have to convert a temperature in degrees Celsius to Fahrenheit. However when I print the temperature in Celsius I get the wrong answer ! Please help ! (The formula is c = (5/9) * (f -32). When I type in 1 for degrees farenheit I get c = -0.0. I have no idea what is wrong :s
Here is the code
import java.io.*; // import/output class
public class FtoC { // Calculates the temperature in Celcius
public static void main (String[]args) //The main class
{
InputStreamReader isr = new InputStreamReader(System.in); // Gets user input
BufferedReader br = new BufferedReader(isr); // manipulates user input
String input = ""; // Holds the user input
double f = 0; // Holds the degrees in Fahrenheit
double c = 0; // Holds the degrees in Celcius
System.out.println("This program will convert the temperature from degrees Celcius to Fahrenheit.");
System.out.println("Please enter the temperature in Fahrenheit: ");
try {
input = br.readLine(); // Gets the users input
f = Double.parseDouble(input); // Converts input to a number
}
catch (IOException ex)
{
ex.printStackTrace();
}
c = ((f-32) * (5/9));// Calculates the degrees in Celcius
System.out.println(c);
}
}
You are doing integer division, and hence 5 / 9 will give your 0.
Change it to floating point division: -
c = ((f-32) * (5.0/9));
or, do the multiplication first (Remove the brackets from division): -
c = (f-32) * 5 / 9;
Since, f is double. Numerator will be double only. I think this way is better.
use this rather:
c = (int) ((f-32) * (5.0/9));// Calculates the degrees in Celcius
as it involves division and you should not use only ints to get proper division
Use this
System.out.println((5F / 9F) * (f - 32F));
You should try using double instead of int as this would lead to loss of precision. Instead of using the whole formula, use one calculation at one time
Example: Use appropriate casting
Double this = 5/9
F - Double 32
Unless explicitly specified otherwise, Java treats all numbers as integers. Since integers cannot store fractional parts of numbers, when integer division is performed, the remainder is discarded. Therefore: 5/9 == 0
Rohit's solution c = (f-32) * 5 / 9; is probably the cleanest (though the lack of explicit types may cause a bit of confusion).
Related
I declared a double variable as below:
double x=56.27d
And then all I tried to do is the following: (56.27*10*10)
System.out.println(xE2);
And this is not working.
There isn't an 'E' operator in java. This would conflict with variable names for one thing. double xE2=x*1e2; In this case, xE2 is a variable name, but I do use 1e2 as a java literal.
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
double d = sc.nextDouble(); // Get input from the user
System.out.println(d * 10 * 10);
// Displaying it using scientific notation
// Format the number rounded up to two places after decimal and into scientific notation
System.out.println(String.format("%.2e", d * 10 * 10));
// Examples of e or E with double literals
double x = 1e2; // 1 * 10 to the power of 2 = 100.0
System.out.println(x);
double y = 1E2; // 1 * 10 to the power of 2 = 100.0
System.out.println(y);
double z = 1e+02; // 1 * 10 to the power of 2 = 100.0
System.out.println(z);
System.out.println(d * 1e2);// i.e. d * 100.0
}
}
A sample run:
Enter a number: 56.27
5627.0
5.63e+03
100.0
100.0
100.0
5627.0
Notes:
Check this to learn more about Formatter.
E or e can be used only with double literals, not double variables.
Feel free to comment in case of any doubt/issue.
You shouldn't use the exponent notation since it is a part of double literal. Try multiplying.
System.out.println(x * 10 * 10)
I suggest you to read java.util.Math library documentation, it includes many scientific functions like Exponents: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html
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.
This are other problems I ran into that is having the same issue. Can anyone point out my logic error in the following below:
Question: A regular polygon is an n-sided polygon in which all sides are of the same length and all angles have the same degree... (Exercise 4.5)
This was my response:
import java.util.Scanner;
public class Exercise04_05 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of sides: ");
double n = input.nextDouble();
System.out.print("Enter the side: ");
double s = input.nextDouble();
double area = n * Math.pow(s, 2) / 4 * Math.tan(Math.PI / n );
System.out.println("The area of the polygon is " + area);
}
}
Please explain where the Logic error is. i commented out the code or else I'll keep getting errors preventing me from submitting the question.
Your formula is wrong and it contains an error.
First / 4 is an integer division which is rounded to an int, so you get mostly an error. You have to use / 4.0 so you get the right division.
The formula for calculation the area of a polygon is
A = 1 / 4 * n * s2 * cot(PI / n)
Note it is cotangens, not tangens. As java.math has no cotangens you have to calculate it by yourself, e.g. 1 / Math.tan(x).
So finally this should work for you:
double area = n / 4.0 * Math.pow(s, 2) / Math.tan(Math.PI / n );
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.
I need to convert Fahrenheit to Celsius in a Java program with methods, a for loop statement, and no user input. It is supposed to display Fahrenheit temperatures 0 through 20 and it's Celsius conversions. Any solutions?
import java.util.Scanner;
public class celsiusTempTable
{
public static void main(String[] args)
{
System.out.println("Fahrenheit to Celsius Conversion Table");
double tempC = celsiusConversion(tempC);
int tempF = fahrenheit(tempF);
displayData(tempF, tempC);
}
public static int fahrenheit(int F)
{
for(F = 0; F <= 20; F++)
{
return F;
}
}
public static double celsiusConversion(double C)
{
Scanner input = new Scanner(System.in);
for(int F = 0; F <= 20; F++)
{
C = (5.0/9.0) * (F - 32);
return C;
}
}
public static void displayData(int F, double C)
{
for(F = 0; F <= 20; F++)
{
System.out.println("\nThe temperature in Fahrenheit is: " + F);
System.out.println("The temperature in Celsius is: " + C);
}
}
}
I'll only give hints.
Without user input. So forget about using a Scanner and System.in.
You need to understand what method arguments and method return values are. Arguments are usually the inputs of a method. And the return value is the output of the method. You're being asked to translate a temperature in fahrenheit degrees to a temperature in celsius degrees. This is a perfect situation where a method is useful. The input of the translation method is thus a unique integer value (the temperature in fahrenheit degrees), and the output is another single integer value (the temperature in celsius degrees).
You must do that 21 times. Once with 0 as input, once with 1 as input, etc. until 20. This means you need a loop, and that at each iteration, you will translate the current temperature (0, 1, 2, etc.) into celsius degrees by calling the translation method, and print the result. Read your text book about for loops. This part should be in the main method.
A quick search and have found the following:
Error: celsius cannot be resolved to a variable
Java Fahrenheit to Celsius loop (with methods)
Fahrenheit to Celsius conversion
Celsius/Fahrenheit conversion error