【问题标题】:Trouble with calling method [duplicate]调用方法有问题[重复]
【发布时间】:2013-10-30 17:49:41
【问题描述】:
public static void main (String[] args) {

   for (double f=0; f<=20;f++) {
      System.out.println(f+":Degrees Fahrenheit converted to Celsius = "+ celsius(f));
   }
}

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

通过这个程序,我试图将华氏温度转换为摄氏温度,当我在运行程序时将方法Celsius 调用到我的main 时,Celsius 的最终结果总是-infinity。我做错了什么?

【问题讨论】:

  • 这个问题已经很好地回答了。但请注意,您可以只使用 return (fahrenheit-32.0)/(5.0/9.0); 您实际上并不需要 cels 变量。
  • 请在 for 循环中为迭代变量使用整数!

标签: java integer-division


【解决方案1】:

你正在做整数除法,它总是返回一个整数。例如5/9 返回 0。

改为使用双除法5.0/9.0

对于您的代码:

public static double celsius (double fahrenheit) {
    return (fahrenheit - 32) / (5.0 / 9.0);
}

我们可能应该将这个问题作为重复问题关闭,因为它已被多次询问。例如:fahrenheit-to-celsius-conversion-yields-only-0-0-and-0-0

【讨论】:

    【解决方案2】:

    (5/9)是一个整数除法,它总是返回0

    应该是:(5.0/9.0)

    【讨论】:

      猜你喜欢
      • 2018-12-21
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      相关资源
      最近更新 更多