有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java转换表

我的任务是创建一个转换表,我不明白为什么一边的输出在另一边完成循环时重复。有人能帮忙吗?下面是我的代码:

public class Conversion {

    public static double celsiusToFahrenheit(double celsius) {
        // make conversion
        double f = (celsius * 9 / 5) + 32;
        return f;

    }

    public static double fahrenheitToCelsius(double fahrenheit) {
        // make conversion
        double c = (fahrenheit - 32.0) * 5 / 9.0;
        return c;

    }

    public static void main(String args[]) {

        double c;
        double f;
        //Display table
        System.out.println("Celsius \t Fahrenheit \t | \tFahrenheit \t Celsius");

        //When i = 40, if i is greater than, or equal to 31, decriment until false
        for (double i = 40; i >= 31; i--) {
            c = i;

            //When j = 120, if j is greater than, or equal to 30, decriment by 10 until false
            for (double j = 120; j >= 30; j -= 10) {
                f = j;

                //Show result
                System.out.println(c + "\t\t " + (Math.round(celsiusToFahrenheit(c) * 10.0) / 10.0) + "\t\t |\t" + f + "\t\t" + (Math.round(fahrenheitToCelsius(f) * 100.0) / 100.0));

            }
        }
    }
}

共 (2) 个答案

  1. # 1 楼答案

    您的输出与您描述的一样,因为每次执行外部for循环(一个用于将摄氏度转换为摄氏度)时,都会执行10次内部for循环(一个用于将摄氏度覆盖到华氏度)

  2. # 2 楼答案

    这是因为您引入了嵌套循环

    for (double i = 40; i >= 31; i ) {
        c = i;
    
        //When j = 120, if j is greater than, or equal to 30, decriment by 10 until false
        for (double j = 120; j >= 30; j -= 10) {
            f = j;
    
            //Show result
            System.out.println(c + "\t\t " + (Math.round(celsiusToFahrenheit(c) * 10.0) / 10.0) + "\t\t |\t" + f + "\t\t" + (Math.round(fahrenheitToCelsius(f) * 100.0) / 100.0));
    
        }
    }
    

    想象一个双圈,就像手表的指针一样。内环比外环移动得快(就像分针比时针移动得快)。这意味着,对于摄氏循环中的每一次迭代,我们在华氏循环中有十次迭代,就像我们在看一个表面一样(在这种情况下,我们每1小时有60分钟)

    作为提示,您实际上可以在循环中声明多个变量以进行迭代。您需要调整循环条件的边界,以便获得所需的结果,但这只是一个开始

    //When i = 40, if i is greater than, or equal to 31, decriment until false
    //When j = 120, if j is greater than, or equal to 30, decriment by 10 until false
    for (double i = 40, j = 120; i >= 31 && j >= 30; i , j -= 10) {
        c = i;
        f = j;
        //Show result
        System.out.println(c + "\t\t " + (Math.round(celsiusToFahrenheit(c) * 10.0) / 10.0) + "\t\t |\t" + f + "\t\t" + (Math.round(fahrenheitToCelsius(f) * 100.0) / 100.0));
    }