从华氏温度转换为摄氏温度

use*_*261 8 c#

我想把华氏温度转换成摄氏温度.
做以下我总是得到零:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Celcius_Farenheit_Converter
{
class Program
{

    static double Celcius(double f)
    {
        double c = 5/9*(f - 32);

        return c;
    }
    static void Main(string[] args)
    {
        string text = "enter a farenheit tempature";
        double c = Celcius(GetTempature(text));
        Console.WriteLine("the tempature in Celicus is {0}", c);

        Console.ReadKey(true);

    }

    static double GetTempature(string text)
    {
        Console.WriteLine(text);
        bool IsItTemp = false;
        double x = 0;

        do
        {
            IsItTemp = double.TryParse(Console.ReadLine(), out x);
        } while (!IsItTemp);

        return x;

    }
}
}
Run Code Online (Sandbox Code Playgroud)

你能帮我解决一下吗?

p.s*_*w.g 33

5/9 执行整数除法 - 也就是说,它总是丢弃小数部分 - 所以它总是返回0.

5.0/9.0 执行浮点除法,并将返回预期的0.55555 ...

试试这个:

static double Celcius(double f)
{
    double c = 5.0/9.0 * (f - 32);

    return c;
}
Run Code Online (Sandbox Code Playgroud)

进一步阅读

  • @Moop除非你试图表示温度*差异*大于273.15°C或[温度低于0°K](https://en.wikipedia.org/wiki/Negative_temperature) - 这并不完全闻所未闻.在这两种情况下,此函数的输入将小于-459.67°F,因此可以假设这是实际意图. (2认同)

Son*_*nül 12

整数除法更改为浮点除法 ;

double c = (5.0 / 9.0) * (f - 32);
Run Code Online (Sandbox Code Playgroud)

C# Specification $7.7.2 Division operator;

整数除法:

除法将结果舍入为零,结果的绝对值是小于两个操作数的商的绝对值的最大可能整数.当两个操作数具有相同符号时,结果为零或正,当两个操作数具有相反符号时,结果为零或负.

正如弗雷德里克所说,只将你的一个变量转换为浮点类型也足以进行计算.(5 / 9f5f / 9给出正确的解决方案)

  • +1对我来说似乎是一个很好的答案.我猜仇恨是hatin'. (4认同)