【问题标题】:convert between Celsius and Fahrenheit using method使用方法在摄氏和华氏之间转换
【发布时间】:2020-02-05 15:09:53
【问题描述】:

尝试使用方法进行转换,但是运行的时候什么都没有做,我做错了什么?

java

    ...
    Scanner input = new Scanner(System.in);
    int selection = 0;

    switch selection {
    case 1:
        int k = input.nextInt();
        System.out.println(celsius(k));
        break;

    case 2:
        int j = input.nextInt();
        System.out.println(fahrenheit(j));
        break;
    }
    ...

public static double fahrenheit(double celsius) {
    double fahrenheit;
    fahrenheit = 9 / 5 * (celsius + 32);
    return fahrenheit;
}

public static double celsius(double fahrenheit) {
    double celsius;
    celsius = 5 / 9 * (fahrenheit - 32);
    return celsius;
}

    ...
    plpStyleData.setStatus(ActionResponseStatus.SUCCESS);
    return plpStyleData;
}

【问题讨论】:

  • "但是运行时它什么也没做" 你是怎么运行它的?就目前而言,这不是有效的 Java 代码。但即使在这种情况下,当您尝试编译它时也会收到一条错误消息。
  • 您没有从扫描仪中获得用户的选择。您只是将选择设置为 0 并且永远不会更改它。由于开关没有0 的情况,因此开关中的任何代码都不会运行。这就是为什么您应该始终拥有default 案例的原因。您可以打印出类似“Invalid selection X”(其中 X 是选择)之类的内容,这将为您提供足够的信息来确定问题所在。
  • 请注意,9/5 将是 1,而 5/9 将是 0,因为它们是 int 的。您需要使用 9.0/5.0 来强制编译器为您的算术使用双精度数
  • 分号很好。适当的缩进是好的。完整、可编译的代码 sn-ps 很好。

标签: java methods switch-statement


【解决方案1】:

因为selection = 0 所以开关不会进入case 1:case 2: 部分。您可能希望将其设置为 input.nextInt(),以便它首先要求输入。

【讨论】:

    【解决方案2】:

    这是不对的:

    华氏度 = 9 / 5 * (摄氏度 + 32)

    (100C + 32) * 9/5 = 237.6F 不正确。

    应该是:

    (100C * 9/5) + 32 = 212F

    (212F - 32) * 5/9 = 100C,所以这部分是正确的。

    【讨论】:

      【解决方案3】:
      212F to C
      C = (F - 32) * 5/9.
      C = (212 - 32) * 5/9.
      C =  180 * 5/9. = 100.
      
      100C to F
      F = (C * 9/5.) + 32.
      F = (100 * 9/5.) + 32.
      F = (180 + 32) = 212
      

      现在找点乐子。需要两者都以(T - offset)*scale的形式获取

      
      C = (F - 32) * 5/9  
      
      F = (C * 9/5) + 32
      5/9F = C + 32*5/9 = C + 160/9.
      
      F = (C + 160/9.)*9/5 
      

      临时转换生成器。获取常量并生成临时转换器。

        BiFunction<Double,Double, DoubleFunction<Double>> temp = 
                  (offset, scale) -> (t)->((int)((t - offset)*scale*1000)/1000.);
      
         DoubleFunction<Double> toCelsius = temp.apply(32., 5./9.);
         DoubleFunction<Double> toFahr = temp.apply(-160./9., 9./5.);
      
         System.out.println(toCelsius.apply(212));  //prints 100.
         System.out.println(toFahr.apply(37));      //prints 98.6
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-14
        • 1970-01-01
        • 2018-08-10
        • 2021-06-17
        • 1970-01-01
        • 1970-01-01
        • 2017-11-30
        • 1970-01-01
        相关资源
        最近更新 更多