[英]Why is my c# program returning 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);
}
}
}
I have commented on what is happening in my code as much as possible. 我已经尽可能地评论了我的代码中发生的事情。 The program stores Fahrenheit as a string and converts it to a decimal fine.
该程序将华氏温度存储为字符串并将其转换为十进制精度。 However, celcius = 0 instead of the correct number at the point where celcius = celcius = ((fahrint) - 32) * (5 / 9);.
但是,celcius = 0而不是celcius = celcius =((fahrint) - 32)*(5/9);的点上的正确数字。 I am aware I spelt celcius wrong, but I do not believe it hase effected the code.
我知道我拼错了celcius,但我不相信它影响了代码。 Any solutions?
有解决方案吗
Thanks! 谢谢!
Integer Division. 整数部。
5 / 9
is always 0
5 / 9
始终为0
(fahrint - 32) * (5 / 9)
^^^
You need to cast at least one of those values to a decimal
: 您需要将这些值中的至少一个强制转换为
decimal
:
celcius = (fahrint - 32) * (5M / 9);
//5 is of type Decimal now
All literal numbers are of type integer
by default. 默认情况下,所有文字数字都是
integer
类型。 When doing integer division, the result is "rounded" down to the nearest whole number, in this case 0
. 进行整数除法时,结果将“舍入”到最接近的整数,在本例中为
0
。 So the result is always 0. 所以结果总是0。
You need to declare one of those as a decimal
to force it to not perform integer division using m
: 您需要将其中一个声明为
decimal
以强制它不使用m
执行整数除法:
celcius = ((fahrint) - 32) * (5m / 9); //5 is now a decimal
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.