Reputation: 686
I'm trying to do a simple operation where I display the value of PI to a user declared decimal length. For instance, if a user enters 2, PI will print out 3.14. However, I keep getting an ArgumentsOutOfBounds
error. Can anyone explain to me what I'm doing wrong?
class PiToDecimalPlaces{
public static void Main(){
int decimalPlaces = (int)Console.Read();
Console.WriteLine(Round(decimalPlaces));
}
public static double Round(int places){
double piToPlaces = Math.Round(Math.PI, places);
return piToPlaces;
}
}
Upvotes: 0
Views: 316
Reputation: 10393
When you directly read using Console.Read()
, you're reading the ASCII
value of input into the decimalPlaces
.
So if you entered 2
, the value of decimalPlaces
would be 50
.
What you need to do is use Console.ReadLine()
and do int.TryParse()
on the input, and then pass it to your Round()
method.
string strNum = Console.ReadLine();
int decimalPlaces;
int.TryParse(strNum, out decimalPlaces);
Console.WriteLine(Round(decimalPlaces));
Upvotes: 0
Reputation: 8541
Please modify the line you are reading value from console to,
int decimalPlaces = Convert.ToInt32(Console.ReadLine());
Upvotes: 0
Reputation: 4394
Couple of things.
First: The below line is logically incorrect. The output returned by Read is a char
in the int
variable
int decimalPlaces = (int)Console.Read();
What you need is
int decimalPlaces = int.Parse(Console.ReadLine());
Second: Your function should really use decimal
and not double
when you want to do fixed point precision since double
is a floating point precision value
public static decimal Round(int places){
decimal piToPlaces = Math.Round((decimal)Math.PI, places);
return piToPlaces;
}
This should fix your exception and also, avoid any potential Floating Point Precision issue
Upvotes: 2