c# - 如何求两个数相除的小数余数?

标签 c# math decimal division

所以我试图制作一个脚本,用户输入他们需要行驶的英里数和每小时行驶的英里数,脚本输出他们必须行驶的剩余小时和分钟。我一直在尝试使用 % 来查找剩余的行驶里程/英里每小时,但它输出了错误的数字。有没有办法只从两个相除的数字中得到小数?例如,如果我执行 100/65,我得到的输出约为 1.538,我只想使用 0.538。但是当我使用 100%65 时,我得到 35。这是我当前的脚本供引用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TimeCalculator
{
     class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to the Travel Time Calculator");
            string answer;
            //creates variable for the answer
            do
            //creates loop to continue the application
            {
                string grade;
               //Console.WriteLine(100-(int)((double)100/65)*65);
                Console.WriteLine(" ");
                Console.Write("Enter miles: ");
                Decimal val1 = Convert.ToDecimal(Console.ReadLine());
               //converts input to decimal allowing user to use decimals
                Console.Write("Enter miles per hour: ");
                Decimal val2 = Convert.ToDecimal(Console.ReadLine());
                //converts input to decimal allowing user to use decimals
                Console.WriteLine(" ");
                Console.WriteLine("Estimated travel time");
                Console.WriteLine("Hours: " + (((int)val1 / (int)val2)));
                //converts values to integers and divides them to give hours traveled
                //double floor1 = Math.Floor(((double)val1/(double)val2));
                 Console.WriteLine("Minutes: " + (Decimal.Remainder((decimal)val1, (decimal)val2)));
            //converts values to double and gets the remainder of dividing both values to find minutes
            Console.WriteLine();
            //enters one line
            Console.Write("Continue? (y/n): ");
            answer = Console.ReadLine();
            //the string is equal to what the user inputs
            Console.WriteLine();
        }
        while (answer.ToUpper() == "Y");
        //if y, the application continues

}
}

最佳答案

100/65 是 integer division 。你需要的是

double d = (100d / 65) % 1;

这将为您提供0.53846153846153855

关于c# - 如何求两个数相除的小数余数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28567562/

相关文章:

python - 为什么 pythondecimal.Decimal 精度与 equable args 不同?

ios - 十进制转二进制的方法Objective-C

c# - 为什么 C# 编译器会产生方法调用以在 IL 中调用 BaseClass 方法

c# - 检查 IsDisposed 和 Disposing 时为 "Cannot access a disposed object"

.net - 如何在 VB.NET 中比较小数点后两位的数字

c++ - 不使用 sqrt 函数求平方根?

algorithm - IsPointInside() 用于曲线轮廓

c# - 基于条件的linq语法调用方法

c# - WCF XmlSerializer 程序集没有加速第一个请求

php - -13 % 64 = -13 在 PHP 中如何实现?