为什么我的c#程序返回0?

时间:2015-10-02 17:05:04

标签: c#

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);



        }
    }
}

我已经尽可能地评论了我的代码中发生的事情。该程序将华氏温度存储为字符串并将其转换为十进制精度。但是,celcius = 0而不是celcius = celcius =((fahrint) - 32)*(5/9);的点上的正确数字。我知道我拼错了celcius,但我不相信它影响了代码。任何解决方案?

谢谢!

2 个答案:

答案 0 :(得分:6)

整数师。 <li><a>{{ Auth::user()->name }}<br/><em>{{ -- CONTROLLER METHOD RESULT HERE --- }}</em></a></li> 始终为5 / 9

0

您需要将至少其中一个值投射到(fahrint - 32) * (5 / 9) ^^^

decimal

答案 1 :(得分:2)

默认情况下,所有文字数字都是integer类型。在进行整数除法时,结果为&#34;舍入&#34;降至最接近的整数,在本例中为0。所以结果总是为0。

您需要将其中一个声明为decimal,以强制它不使用m执行整数除法:

celcius = ((fahrint) - 32) * (5m / 9); //5 is now a decimal