简体   繁体   中英

Setting PI decimal places to user given number of places in C#

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;
    }
}

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

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));

请修改您正在从控制台读取值的行,

int decimalPlaces = Convert.ToInt32(Console.ReadLine());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM