我的任务是制作一个简单的摄氏温度到华氏度或华氏度到摄氏温度的转换器。我的实验室老师带走了我的大部分时间,但在解释事情上做得不好。我知道它的大部分功能以及它如何交互,代码有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;
}
}
答案 0 :(得分:2)
一次提出一个问题......
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?
参数(如果有)在括号中声明,作为一个类型后跟一个参数名称。我们在这里有一个名为float
f
参数
但是有几个错误。在java中,整数除法产生整数结果,这意味着截断非整数部分,因此5/9
是int
0
。但要修复它,只需删除括号!:
public static float ftoC(float f) {
return (f-32)*5/9;
}
通过删除括号,问题得到解决,因为在java中,如果一个的操作数为float
而另一个<{1}},则结果为{{1} }。此计算首先从int
中减去float
- 给出int
。然后它乘以float
float
- 给出int
。然后它除以5
float
- 给出int
!
请注意,我没有打扰局部变量 - 只需返回计算。代码越少越好。
答案 1 :(得分:1)
float output = ftoC(input); // I'm kind of confused as to why she told me to put the variable inside of the ();
这样您就可以将变量传递给函数ftoC
。
System.out.println(ftoC(input)); //Same here with the variables :(
与上述相同。数据如何进入函数或方法?
public static float ftoC(float f) //This is a method line, but why is float f inside the parenthesis?
因为你必须告诉程序你的数据类型是什么,所以它知道如何将它放在内存中。否则,它不知道您希望数据类型在内存中有多大。此外,如果您要将int
传递给期望float
的方法,则该程序会表现出不同的行为。
答案 2 :(得分:1)
首先,这不符合您的期望:
(f-32)*(5/9);
5/9作为整数除法执行,因此它等于0.任何乘以0的也是0。 您需要将5和/或9转换为float:
(f-32)*(5f/9f);