I have been trying to see what I did wrong in my code, but I counldn't find out. This is my second java program after the "Hello World". Could anyone help me to find out why I did not get the right answer for this. For example, if we enter 43 Celsius it's going to give us 109.4 in Fahrenheit, but I got 75.0 all the time. Thanks in advance

import java.util.*; // this is for Scanner

public class ChapterTwoAssign {

    public static void main(String args[]){

        // Create a Scanner for input
        Scanner input = new Scanner(System.in);

        /*Statements for converting Celsius to Fahrenheit */
        System.out.println("Enter a degree in Celsius: ");
        int celsius = input.nextInt();

        // Convert Celsius to Fahrenheit
        double fahrenheit = (9 / 5) * celsius + 32;
        System.out.println( celsius + " Celsius is " + fahrenheit + " Fahrenheit ");
    }

}

Recommended Answers

All 5 Replies

( 9 / 5 )

9 and 5 are both ints, so the division is done in integer arithmetic, giving the result 1

He is right so try something like this:

double fahrenheit = ((9 * celsius) / 5 ) + 32;

or

double fahrenheit = ( 1.8 * celsius ) + 32;

Your first suggestion will only work if 9 * celsius is divsible by 5. celsius is defined as an int.

rch1231
Yes, that's a solution, but I hoped the OP would get the benefit of working out the solution for himself!

ddanbe
it will work (compile and execute without errors), so the real question is what does the OP want to do about fractions in the result? Declaring C as int and F as double seems to indicate a schizophrenic approach to temperature values :)

@JamesCherrill you are right. (9/5) are int numbers so the result should be an integer. I tried to change one of them to a decimal num and it worked. Thank you.

@rch1231 Yup. I tried this --double fahrenheit = ( 1.8 * celsius ) + 32; and I got the right answer for that. Thanks you guys a lot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.