c# - How to check for a double type response in an if statement -


i'm trying check if user's response double or int, int specific, whereas double not, made right mess of explaining it, here's code:

console.writeline("\n 2) q: how old sally? \n"); int nsallyage = convert.toint32(console.readline()); double dsallyage = convert.todouble((nsallyage));  if (nsallyage == 62 || dsallyage == 62.0) {     // increase score     suser1score++;     console.writeline("\n a: correct, sally's age 62, have been awarded 1 point. \n");     console.readline(); }  

what i'm trying do, instead of dsallyage has equal 62.0, has equal double figure.

i approach problem first creating method gets double user (that will, of course, accept int). removes error handling main code.

note in code below, math.truncate can replaced math.floor, same result:

private static double getdoublefromuser(string prompt) {     double input;      while (true)     {         if (prompt != null) console.write(prompt);         if (double.tryparse(console.readline(), out input)) break;         console.writeline("sorry, not valid number. please try again.");     }      return input; } 

then, in main code, number user, , use math.truncate method read first part of double passed in user (this sounds want do). means if user enters 62 62.0 62.999, truncate result '62':

double nsallyage = getdoublefromuser("2) q: how old sally? ");  if (math.truncate(nsallyage) == 62) {     // increase score     suser1score++;     console.writeline("a: correct, sally's age 62, have been awarded 1 point.");     console.readline(); }  

other alternative ways use are:

int sallyage = math.truncate(getdoublefromuser("2) q: how old sally? "));  if (sallyage == 62) {     // increase score     suser1score++;     console.writeline("a: correct, sally's age 62, have been awarded 1 point.");     console.readline(); } 

or, use input function returns int in first place:

private static int getintfromuser(string prompt) {     return math.truncate(getdoublefromuser(prompt)); } 

Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

[C++][SFML 2.2] Strange Performance Issues - Moving Mouse Lowers CPU Usage -

ios - Possible to get UIButton sizeThatFits to work? -