gpt4 book ai didi

java - 如何使用循环在java中制作表格

转载 作者:行者123 更新时间:2023-12-02 04:38:27 27 4
gpt4 key购买 nike

在类里面我遇到了以下问题:

编写一个包含以下两个方法的类:

/** Convert from Celsius to Fahrenheit */
public static double celsiusToFahrenheit(double celsius)

/** Convert from Fahrenheit to Celsius */
public static double fahrenheitToCelsius(double fahrenheit)

The formula for te conversion is:
fahrenheit = (9.0 / 5) * celsius + 32
celsius = (5.0 / 9) * (fahrenheit - 32)

编写一个测试程序,调用这些方法来显示下表:

celsius  Fahrenheit  |  Fahrenheit  celsius
___________________________________________
40.0 104.0 | 120.0 48.89

39.0 102.2 | 110.0 43.33

...

32.0 89.6 | 40.0 4.44

31.0 87.8 | 30.0 -1.11
<小时/>

我尝试过以下代码:

public static double celciusToFahrenheit(double celcius) {
double fahrenheit = (9.0 / 5) * celcius + 32;
return fahrenheit;
}

public static double fahrenheitToCelcius(double fahrenheit) {
double celcius = (5.0 / 9) * (fahrenheit - 32);
return celcius;
}
public static void main(String[] args) {
// TODO Auto-generated method stub

System.out.println("Celcius\tFahrenheit\t|\tFahrenheit\tCelcius");

for (int i = 0; i < 10; i++ ) {
for (int a = 40; a > 30; a--) {
System.out.print(i + "\t" + celciusToFahrenheit(i) + "\t|\t");
}
for (int b = 120; b > 30; b -= 10) {
System.out.print(i + "\t" + fahrenheitToCelcius(i) + "\n");
}
}

}

问题在于,在“主”循环中,它首先循环第一个循环,然后运行第二个循环。但为了显示表格,它必须在第一个循环之间进行更改。或者我是否必须采取完全其他的方法。

最佳答案

那里有太多的 for 循环。您只需要一个:

for (int i = 0; i < 10; i++ ) {
double celcius = 40 - i;
double convertedCelcius = celciusToFahrenheit(celcius);
double fahrenheit = 120 - (i * 10);
double convertedFahrenheit = fahrenheitToCelcius(fahrenheit);

System.out.print(celcius + "\t" + convertedCelcius + "\t|\t" + fahrenheit + "\t" + convertedFahrenheit + "\n");
}

关于java - 如何使用循环在java中制作表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32583375/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com