为什么我的c#程序返回0?
我已经尽可能多地评论了代码中发生的事情。程序将华氏温度存储为字符串,并将其转换为十进制。但是,celcius=0,而不是celcius=celcius=((fahrint)-32)*(5/9);。我知道我把celcius拼错了,但我不相信这是代码。有什么解决办法吗为什么我的c#程序返回0?,c#,C#,我已经尽可能多地评论了代码中发生的事情。程序将华氏温度存储为字符串,并将其转换为十进制。但是,celcius=0,而不是celcius=celcius=((fahrint)-32)*(5/9);。我知道我把celcius拼错了,但我不相信这是代码。有什么解决办法吗 谢谢 整数除法5/9始终为0 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Thr
谢谢 整数除法<代码>5/9始终为
0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fahrenheit_to_Celsius_Converter
{
class Program
{
static void Main(string[] args)
{//Prompt user to enter a temperature
Console.WriteLine("Please enter the temperature in fahrenheit you want to convert");
//Sets variable fahr to the number entered
string fahr = Console.ReadLine();
//Just for testing debugging purposes displays what data is stored in fahr.
Console.WriteLine(fahr);
//Initializes an integer fahrint
int fahrint;
fahrint = int.Parse(fahr);
//Just for testing debugging purposes displays what data is stored in fahrint.
Console.WriteLine(fahrint);
//Initializes an integer celcius
decimal celcius;
//Does the calculation that stores to a variable called celcius
celcius = ((fahrint) - 32) * (5 / 9);
//At this point the celcius variable print 0. It should print 5 if 41 is entered
Console.WriteLine(celcius);
string celciusstring;
celciusstring = celcius.ToString();
Console.WriteLine(celciusstring);
}
}
}
您需要将这些值中的至少一个强制转换为十进制
:
(fahrint - 32) * (5 / 9)
^^^
默认情况下,所有文字数字的类型均为
integer
。进行整数除法时,结果将向下“四舍五入”到最接近的整数,在本例中为0
。所以结果总是0
您需要将其中一个声明为十进制
,以强制它不使用m
执行整数除法:
celcius = (fahrint - 32) * (5M / 9);
//5 is of type Decimal now
将
5
声明为double
,然后将结果转换为十进制是很奇怪的。如果将5声明为十进制,则不需要强制转换。很好。我没有检查最后的类型。使用十进制而不是双精度。在这样的计算中不要使用十进制。使用双重密码。(十进制最适合用于财务计算。)
celcius = ((fahrint) - 32) * (5m / 9); //5 is now a decimal