Oct*_*cto 2 c# math decimal division
因此,我正在尝试编写一个脚本,其中用户输入了他们需要行驶的英里数和每小时行驶的英里数,并且脚本输出了他们必须行驶的剩余小时数和分钟数。我一直在尝试使用%来查找行驶的英里数/ 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
}
}
Run Code Online (Sandbox Code Playgroud)
100/65是整数除法。您需要的是
double d = (100d / 65) % 1;
Run Code Online (Sandbox Code Playgroud)
这会给你 0.53846153846153855