gpt4 book ai didi

java - 温度计类逻辑错误

转载 作者:行者123 更新时间:2023-12-02 11:59:39 24 4
gpt4 key购买 nike

我正在尝试创建一个具有单个构造函数的类,该构造函数接受 double 温度(以摄氏度为单位),如果温度小于 -273.15,则将其设置为 -273.15。它还计算不同测量单位的其他温度,但这并不重要。由于某种原因,我收到一个逻辑错误,该错误无法纠正小于 -273.15 到 -273.15 的输入。

public class TemperatureC
{


private double temperature;


public TemperatureC(double c)
{
if (temperature < -273.15)
{
temperature = -273.15;
}
else
{
temperature = c;
}
}

public TemperatureC()
{
temperature = -273.15;
}

public double getC()
{
return temperature;
}

public double getF()
{
return ((temperature * 1.8) + 32);
}

public double getK()
{
return (temperature + 273.15);
}

public void setC(double c)
{
if (temperature >= -273.15)
{
temperature = c;
}

}

}

这就是使用该类的原因。

import java.util.Scanner;

public class TemperatureTester
{
public static void main(String[] args)
{
Scanner thermometer = new Scanner(System.in);
TemperatureC temp = new TemperatureC();

System.out.printf("Please enter the initial temperature:");
double intialTemp = thermometer.nextDouble();
temp.setC(intialTemp);

System.out.println("The current temperature in Celsius is:" + temp.getC());
System.out.println("The current temperature in Fahrenheit is:" + temp.getF());
System.out.println("The current temperature in Kelvin is:" + temp.getK());

System.out.printf("Please enter a new temperature:");
double secondTemp = thermometer.nextDouble();
temp.setC(secondTemp);

System.out.println("The current temperature in Celsius is:"+ temp.getC());
System.out.println("The current temperature in Fahrenheit is:"+ temp.getF());
System.out.println("The current temperature in Kelvin is:"+ temp.getK());

}
}

这是我的错误输出:

Please enter the initial temperature:-900
The current temperature in Celsius is:-900.0
The current temperature in Fahrenheit is:-1588.0
The current temperature in Kelvin is:-626.85
Please enter a new temperature:-900
The current temperature in Celsius is:-900.0
The current temperature in Fahrenheit is:-1588.0
The current temperature in Kelvin is:-626.85

它应该将小于 -273.15 的输入纠正为 -273.15。

最佳答案

您的问题是您正在检查构造函数的默认值。首先将温度设置为 c 或对照 c 进行检查。

public TemperatureC(double c)
{

temperature = c;

if (temperature < -273.15)
{
temperature = -273.15;
}

这应该有效,作为副作用,不再需要 else

关于java - 温度计类逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47358770/

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