gpt4 book ai didi

java - 使用 3 种方法将摄氏温度转换为华氏温度以及将华氏温度转换为摄氏温度

转载 作者:行者123 更新时间:2023-12-01 18:36:00 25 4
gpt4 key购买 nike

我的任务是制作一个简单的摄氏度到华氏度或华氏度到摄氏度的转换器。我的实验室老师引导我完成了大部分内容,但在解释方面做得很糟糕。我知道它的大部分功能以及它如何交互,并且代码有 0 个错误,但没有正确执行转换。我将发布代码,并对我不理解的部分进行评论,但我真正需要的是有人解释我不理解的部分,并且修复脚本以便它会很棒执行正常。不懂的地方我会评论。

 import java.util.Scanner;

public class ExerciseOne
{
public static void main( String[] args )
{

int choice;


System.out.println( "What would you like to do? \n 1 - Fahnrenheit to Celsius \n 2 - Celsius to Fahrenheit \n 3 - Quit" );
Scanner dylan = new Scanner(System.in);
choice = dylan.nextInt();



if (choice == 1)
{
System.out.println( "What number do you want to convert to Celsius?" );
float input = dylan.nextFloat();
float output = ftoC(input); // I'm kind of confused as to why she told me to put the variable inside of the ();
System.out.println(ftoC(input)); //Same here with the variables :(


}

if (choice == 2)
{
System.out.println( "What number do you want to convert to Fahrenheit?" );
float input = dylan.nextFloat();
float output = ctoF(input);
System.out.println(ctoF(output));
}

if (choice == 3)
{
System.out.println( "Exiting application.");
}

}

public static float ftoC(float f) //This is a method line, but why is float f inside the parenthesis?
{
float celsius = (f-32)*(5/9);
return celsius;
}

public static float ctoF(float c) //Same thing goes for here
{
float fahrenheit = (c)*(9/5) + 32;
return fahrenheit;
}

}

最佳答案

一次回答一个问题...

float output = ftoC(input); // I'm kind of confused as to why she told me to 

将变量放在()内;

这里 ftoC 是一个方法,input 被传递给它

System.out.println(ftoC(input)); //Same here with the variables :(

再次调用该方法。无意义。只需打印上一次调用的结果即可:

System.out.println(output);

此外,我会更改这些行:

float input = dylan.nextFloat();
float output = ftoC(input);
System.out.println(output);

致:

System.out.println(ftoC(dylan.nextFloat())); 

您不需要这些局部变量,只需将每个返回值直接传递到下一个方法即可。

<小时/>
public static float ftoC(float f)  //This is a method line, but why is float f inside the parenthesis?

参数(如果有)在括号中声明,作为类型后跟参数名称。这里我们有一个名为 f

float 参数<小时/>

但是有几个错误。在java中,整数除法的结果是整数,这意味着截断非整数部分,所以5/9就是int 0 。但要修复它,只需删除括号即可!:

public static float ftoC(float f) {
return (f-32)*5/9;
}

通过删除括号,问题就得到了解决,因为在 java 中,如果一个操作数是 float 而另一个int,则结果是浮点。此计算首先从 float 中减去 int - 得到 float。然后它乘以 int 5 - 给出一个 float。然后除以 int 9 - 得到一个 float!

还要注意,我没有关心局部变量 - 只是返回计算结果。代码越少越好。

关于java - 使用 3 种方法将摄氏温度转换为华氏温度以及将华氏温度转换为摄氏温度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21990139/

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