I am trying to check that the user's response is a double
or int
, but int
is unique, while is not double
, as I have explained it, here is the code:
< Code> console.light line ("\ n 2) question: how old is Sallie? \ N"); Int nSallyAge = Convert.ToInt32 (console .readline ()); Double dSallyAge = Convert. Double (nSallyAge); If (nSallyAge == 62 || dSallyAge == 62.0) {// increase score sUser1Score ++; Console.light line ("\ nA: right, Sally's age is 62, you've been awarded 1 point. \ N"); Console.ReadLine (); }
What I'm trying to do, is equal to dSallyAge
instead of 62.0
, it's just any double
figure
I can make a method before this problem a double user (which, of course, also Will accept an integer) This handles the error with your main code.
Note , Math.Truncate
to Math.Floor
in the code below, with the same result:
Private Static Double GetDoubleFromUser (String Prompt) {Double Input; Whereas (true) {if (prompt! = Null) console Write (Quick); If (Double Tripers (console) .Redline (), Break Out)); Console.light line ("Sorry, that is not a valid number, please try again."); } Return input; }
Then, in my main code, I will get the number from the user, and read the first part of the bus to use the Math.Truncate
method. Double users Passed by (this is what it feels like you want to do). This means that if the user enters anything from 62 to 62.0 to 62.999, then the result will be reduced to '62':
double nSallyAge = GetDoubleFromUser ("2) Question: How old is Sally? "); If (math.Tnktak (nSallyAge) == 62) // // increase score sUser1Score ++; Console.light line ("A: right, Sally's age is 62, you have been awarded 1 point."); Console.ReadLine (); }
Other alternative ways to use it are:
int sallyAge = Math.Truncate (GetDoubleFromUser ("2") Question: How old is Sally? ")); If (sallyAge == 62) {// increase score sUser1Score ++; Console.light line ("A: right, Sally's age is 62, you have been awarded 1 point."); Console.ReadLine (); }
Or, you can use an input function which returns an integer to the first position:
Private static id GetIntFromUser (string prompt) {Return Mathematics .Truncate (GetDoubleFromUser (Speedy)); }
No comments:
Post a Comment