[编辑] @Ryan感谢您的解决方案!但是,现在我收到错误" c在第一种方法中定义"当我没有在第二次重新定义时。
public class cf {
public static void methodOne (double c, double f) {
double c = 40;
double f;
System.out.println("Celsius Fahrenheit");
while (c >= 30) {
f = c * 9/5 +32;
System.out.println((c) + " "+Math.round(f*100.0)/100.0);
c--;
}
}
public static void methodTwo (double ce, double fa) {
double ce;
double fa = 120;
System.out.println("Fahrenheit Celsius");
while (fa >= 30) {
ce = fa * 5/9 -32;
System.out.println((fa) + " "+Math.round(ce*100.0)/100.0);
fa--;
}
}
}
答案 0 :(得分:1)
你的根本问题显然是在循环中错误地实现了从Celsius到Fahrenheit的转换。我会通过提取"牛肉来解决这个问题。您的应用程序,即温度转换(公式为in Wikipedia),变为自己的方法:
/**
* Converts the input Celsius temperature into Fahrenheit degrees, using the
* formula:
*
* <pre>
* (degreesCelsius * 1.8) + 32 = degreesFahrenheit
* </pre>
*
* @param degreesCelsius
* temperature in Celsius degrees
* @return the temperature in Fahrenheit degrees
*/
private static float celsiusToFahrenheit(float degreesCelsius) {
return (degreesCelsius * 1.8f) + 32.0f;
}
您应该将计算与其余代码分开,因为它:
完成上述操作后,其余代码只处理范围的初始化并迭代它:
// define the range
final int cMin = 30;
final int cMax = 40;
// run the conversion
for (int i = cMax; i >= cMin; i--) {
float degreesCelsius = (float) i;
float degreesFahrenheit = celsiusToFahrenheit(degreesCelsius);
System.out.println(String.format("%.1f\t|\t%.1f", degreesCelsius,
degreesFahrenheit));
}
请注意,我已将摄氏度范围声明为int
,因为要求是每次转化之间的一度增量。在计算之前,这些值 cast 到float
s。
您应该在代码中避免使用幻数,这就是为什么范围被定义为一对 final 变量(您也可以从{{{ 1}}数组,如果你想接受用户输入)。如果您不希望它在程序运行之间发生变化,那么该范围也可以定义为args
字段。
最后,实用程序类Formatter
用于通过static final
输出数据。这样可以轻松更改输出中String.format()
值的精度。
答案 1 :(得分:0)
public static void main(String[] args) {
double c=40;
double f;
while(c >= 30){
f = c * 9/5 +32; //°C x 9/5 + 32 = °F
System.out.println(c + "|" + f);
c--;
}
}
答案 2 :(得分:0)
这将根据您的喜好格式化您的代码。它会按要求为您提供输出。
public class Far {
public static void main(String[] args) {
double c = 40;
double f;
System.out.println("Celsius Fahrenheit");
while (c >= 30) {
f = c * 9/5 +32;
System.out.println((c) + " "+Math.round(f*100.0)/100.0);
c--;
}
}
}
答案 3 :(得分:0)
这应该这样做。
System.out.println(String.format("%-10s %-10s","Celsius ","Fahrenheit"));
double f = 30;
double c;
double i = 1;
while (f <= 120) {
f += i * 1 + f;
c = (5.0 / 9.0) * (f - 32);
System.out.println(String.format("%-10s %-10s",(double) Math.round((c / c * 100) * 10) / 10,(double) Math.round((f / f * 100) * 10) / 10));
i++;
}