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

本文关键字:返回 程序 我的 为什么 | 更新日期: 2023-09-27 18:15:38

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 = celcius = ((fahrint) - 32) *(5/9);处,celcius = 0而不是正确的数字。我知道我把celcius拼错了,但我不认为它影响了密码。有解决方案吗?

谢谢!

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

整数除法。5 / 9总是0

(fahrint - 32) * (5 / 9)
                   ^^^  

您需要将这些值中的至少一个强制转换为decimal:

celcius = (fahrint - 32) * (5M / 9);
//5 is of type Decimal now

所有文字数字默认为integer类型。在进行整数除法时,结果被"舍入"到最接近的整数,在本例中为0。所以结果总是0。

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

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