gpt4 book ai didi

java - 类方法未执行正确的计算

转载 作者:行者123 更新时间:2023-12-01 07:05:20 24 4
gpt4 key购买 nike

目前我正在为学校做一个项目,要求如下:

Write a Temperature class that will hold a temperature in Fahrenheit and provide methods to get the temperature in Fahrenheit, Celsius, and Kelvin. The class should have the following field:

  • ftemp: a double that holds a Fahrenheit temperature.

The class should have the following methods:

  • Constructor: The constructor accepts a Fahrenheit temperature (as a double) and stores it in the ftemp field.
  • setFahrenheit: The set Fahrenheit method accepts a Fahrenheit temperature (as a double) and stores it in the ftemp field.
  • getFahrenheit: Returns the value of the ftemp field as a Fahrenheit temperature (no conversion required)
  • getCelsius: Returns the value of the ftemp field converted to Celsius. Use the following formula to convert to Celsius: Celsius = (5/9) * (Fahrenheit - 32)
  • getKelvin: Returns the value of the ftemp field converted to Kelvin. Use the following formula to convert to Kelvin: Kelvin = ((5/9) * (Fahrenheit - 32)) + 273

Demonstrate the Temperature class by writing a separate program tha asks the user for a Fahrenheit temperature. The program should create an instance of the Temperature class, with the value entered by the user passed to the constructor . The program should then call the object's methods to display the temperature in the following format (for example, if the temperature in Fahrenheit was -40):

  • The temperature in Fahrenheit is -40.0
  • The temperature in Celsius is -40.0
  • The temperature in Kelvin is 233.0

这是我当前的代码:

温度(等级)

public class Temperature {

private double ftemp;

public Temperature(double temp)
{
ftemp = temp;
}

public void setFahrenheit(double t)
{
ftemp = t;
}

public double getFahrenheit()
{
return ftemp;
}

public double getCelsius()
{
return (5/9) * (ftemp - 32);
}

public double getKelvin()
{
return ((5/9) * (ftemp - 32)) + 273;

}

}

MPL1(主要源代码)

import java.util.Scanner;

public class MPL1 {

public static void main(String[] args)
{

double input;
Scanner keyboard = new Scanner(System.in);

System.out.print("Enter a Fahrenheit temperature: ");

input = keyboard.nextDouble();

Temperature myTemp = new Temperature(input);


System.out.println("The temperature in Fahrenheit is " +
myTemp.getFahrenheit());
System.out.println("The temperature in Celsius is " +
myTemp.getCelsius());
System.out.println("The temperature in Kelvin is " +
myTemp.getKelvin());

}
}

执行时,它几乎可以正确执行所有操作,但是,使用 getCelsiusgetKelvin 给出的结果为 0.0273.0 无论输入什么数字。

最佳答案

5/9 是整数除法,由于 9 可以除以 5 个零,因此 5/9 = 0。将其转换为 double 型:((double)5/9)

关于java - 类方法未执行正确的计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26564923/

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