到目前为止,我的程序:
import java.util.Scanner;
public class Temperature
{
public static void main(String[] args)
{
int count = 20;
double fahrenheit;
double celsius;
String input;
// Scanner object for keyboard input.
Scanner kb = new Scanner(System.in);
// Get the information.
System.out.print("Enter your starting temperature in Fahrenheit: ");
fahrenheit = kb.nextDouble();
// Display the results in a table.
System.out.println("Fahrenheit Celsius");
System.out.println("-----------------------");
for (fahrenheit = fahrenheit; fahrenheit <= count; fahrenheit += 5)
{
// Calculate
celsius = (fahrenheit - 32)*(5.0 / 9.0);
System.out.printf("%,.2f \t\t\t %,.2f\n", fahrenheit, celsius);
}
}
}
现在我需要做的是生成一张从华氏度到摄氏20度的温度转换表。如果用户输入0,这是您的输出前三行的示例:
华氏度:0 CELSIUS:-17.78
华氏度:5 CELSIUS:-15.00
华氏度:10 CELSIUS:-12.22
等...
问题是,如果输入大于20,它将不会循环正确的时间。
这里是用户输入5会发生什么的示例:
输出:
以华氏温度输入您的起始温度:5
华氏摄氏温度
5.00 -15.00
10.00 -12.22
15.00 -9.44
20.00 -6.67
然后就是输出结束的地方。
有人知道我该怎么做,以便无论用户输入什么,该程序都将显示20 F到C的等效值?
选项1,添加一个计数器并使用它。
for (int i = 0; i < count; i++, fahrenheit += 5)
{
// Calculate
celsius = (fahrenheit - 32)*(5.0 / 9.0);
System.out.printf("%,.2f \t\t\t %,.2f\n", fahrenheit, celsius);
}
选项2,在循环时递减count
(并测试零)。>
for (; count > 0; count--, fahrenheit += 5)
{
// Calculate
celsius = (fahrenheit - 32)*(5.0 / 9.0);
System.out.printf("%,.2f \t\t\t %,.2f\n", fahrenheit, celsius);
}
您的for
循环全乱了:for (fahrenheit = fahrenheit; fahrenheit <= count; fahrenheit += 5)
它正在将温度与计数(fahrenheit <= count
)进行比较。
您需要做的是保留一个单独的index
,该值从0开始,一直到20。这意味着每次都会更改2个变量,即index
和fahrenheit
,以及for循环如下所示:
尝试一下: