【问题标题】:How to get decimal remainder of two numbers divided?如何获得两个数字的小数余数?
【发布时间】:2015-02-17 17:37:19
【问题描述】:

所以我正在尝试制作一个脚本,其中用户输入他们需要旅行的英里数和他们每小时旅行的英里数,脚本输出他们必须旅行的剩余小时数和分钟数。我一直在尝试使用 % 来查找剩余的行驶里程/MPH,但它输出了错误的数字。无论如何只能从两个相除的数字中得到小数吗?例如,如果我做 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

}
}

【问题讨论】:

  • 两个数字的余数和一个数字的小数部分是两个不同的东西。您正在寻找后者。

标签: c# math decimal division


【解决方案1】:

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

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

这会给你0.53846153846153855

【讨论】:

  • @BradleyDotNET 没有double % int,只有double % double 的行为确实与EZI 的示例显示一样。
  • 显然双模不能像我预期的那样工作。很聪明
  • @BradleyDotNET 请注意,% 适用于除int 以外的类型,并且与大多数int-double 运算符一样,将输出double 以避免精度损失跨度>
【解决方案2】:

如果您想要初始值的小时和分钟,那么这应该为您完成(您可能需要在其中进行一些显式转换,这是未经测试的)

var result = va1 / val2;   
var hours = Math.Floor(result);
var minutes = (result - hours) * 60;

【讨论】:

    猜你喜欢
    • 2017-06-27
    • 2017-04-06
    • 2020-09-30
    • 2022-01-03
    • 1970-01-01
    • 2011-04-22
    • 2015-02-10
    • 2019-05-05
    相关资源
    最近更新 更多