JHS*_*IAO 3 c# calculator console-application
在我的if语句"(LengthCalculatorOption == 1)"例如我想要187.96cm转换为英尺和英寸,如6feet 2ins.我怎么做?因为在我当前的代码中,它将显示6.17feet并始终为0ins.我不知道为什么.
static void Main(string[] args) {
double Centimetres = 0.0, Feet = 0.0, Inches = 0.0;
string AnotherConversion = null;
string LengthCalculatorMenu;
int LengthCalculatorOption;
do{
LengthCalculatorMenu = ("Enter 1) Convert centimetres to feet and inches:"
+ "\nEnter 2) Convert feet and inches to centimetres:");
Console.Write(LengthCalculatorMenu);
LengthCalculatorOption = int.Parse(Console.ReadLine());
if (LengthCalculatorOption == 1) {
Console.WriteLine("Please Enter the Centimetres(cm) that you wish to convert to feet and inches");
Centimetres = double.Parse(Console.ReadLine());
Feet = (Centimetres / 2.54) / 12;
Inches = (Centimetres / 2.54) - (Feet * 12);
Centimetres = ((Feet * 12) + Inches) * 2.54;
Console.WriteLine("\nThe equivalent in feet and inches is {0:C} ft {1:G} ins", Feet, Inches);
Console.Write("\nWould you like to make an another conversion? \n\n(Enter Y to make an another conversion/Enter any other key to exit):");
AnotherConversion = Console.ReadLine();
} else if (LengthCalculatorOption == 2) {
Console.WriteLine("Please Enter the Feet");
Feet = double.Parse(Console.ReadLine());
Console.WriteLine("Please Enter the Inches");
Inches = double.Parse(Console.ReadLine());
Centimetres = ((Feet * 12) + Inches) * 2.54;
Console.WriteLine("\nThe equivalent in centimetres is {0:G}cm", Centimetres);
Console.Write("\nWould you like to make an another conversion? \n\n(Enter Y to make an another conversion/Enter any other key to exit):");
AnotherConversion = Console.ReadLine();
} else {
Console.WriteLine("\n\a\t Invalid Option!Option Must be 1 or 2");
}
} while (AnotherConversion == "y" || AnotherConversion == "Y");
Run Code Online (Sandbox Code Playgroud)
试试这个:
Feet = (Centimetres / 2.54) / 12;
int iFeet = (int)Feet;
inches = (Feet - (double)iFeet) * 12;
Run Code Online (Sandbox Code Playgroud)
详细说明:
您将脚定义为double,这意味着它将是十进制值.因此,除非您除以12,否则它可以成为十进制表示.
我的代码所做的是将Feet转换为整数(在这种情况下将其舍入为6).然后我们减去Feet的双重版本(在这种情况下为6.17),等于.17(余数).我们乘以12乘以.17英尺到英寸
编辑
根据斯科特的评论进行扩展,这将是一个不同的方式
int totalInches = (Centimetres / 2.54); // This will take a floor function of Centimetres/2.54
int Feet = (totalInches - totalInches % 12) / 12; // This will make it divisible by 12
int inches = totalInches % 12; // This will give you the remainder after you divide by 12
Run Code Online (Sandbox Code Playgroud)