方法不断返回 0
本文关键字:返回 方法 | 更新日期: 2023-09-27 18:31:50
我试图让Celsius
以华氏温度为参数,然后以摄氏度为单位返回温度
class Exercise1
{
static void Main(string[] args)
{
double fahrenheit;
Console.WriteLine("Enter farenheit: ");
fahrenheit = double.Parse(Console.ReadLine());
double cels;
Exercise1 me = new Exercise1();
cels = me.Celsius(fahrenheit);
Console.WriteLine(cels);
}
public double Celsius(double fahrenheit)
{
double celsius;
celsius = 5 / 9 * (fahrenheit - 32);
return celsius;
}
你的问题是Celsius
函数中的整数除法。此行
celsius = 5 / 9 * (fahrenheit - 32);
将始终为 0,因为 5/9 将被除以整数,这将始终为您提供 0。若要强制浮点除法,如果整数必须是双精度数,则为一个。所以这样做:
celsius = 5.0 / 9 * (fahrenheit - 32);
请注意,5.0 将强制进行浮点除法。
5 / 9
将被视为整数,因此在这种情况下,整个计算都是整数数学。
这意味着你基本上得到了0 * (fahrenheit - 32)
.
将 5 和 9 之一或两个转换为双精度以强制浮点数学运算。