我想把华氏温度转换成摄氏温度.
做以下我总是得到零:
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)
进一步阅读
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 / 9f或5f / 9给出正确的解决方案)