Home > front end >  How can I make my code ask for an Input instead of hard coding the values
How can I make my code ask for an Input instead of hard coding the values

Time:11-11

I'm new to C# so not sure how I can pull this off, in my code I type in the values I need to convert Console.WriteLine(ToFeet(5.17));, how can I prompt for an input like Console.WriteLine("Enter number: ") and output the conversion 4FT 2IN. This could be the same thing but also not sure how to make it a variable(dynamic) so I can call this function elsewhere...

using System;
class Code {

public static string ToFeet(double dec)
{
    return $"{Math.Truncate(dec)} FT {Math.Round(12 * (dec - Math.Truncate(dec)))} IN";
}

static void Main() 
{
    Console.WriteLine(ToFeet(5.17));
}

}

Since I'm new to C#, I didn't know what could I try, I researched for a bit and tried Console.ReadLine() couldn't get my logic to work...

CodePudding user response:

ask input, parse it , then pass to function

  Console.WriteLine("Enter input");
  var inString = Console.ReadLine();
  double input;
  if(Double.TryParse(inString, out input)) {
     Console.WriteLine( ToFeet(input));
  }
  else {
     Console.WriteLine("Invalid input");
  }
  
  •  Tags:  
  • c#
  • Related