2017-08-30 92 views
0

我试图做一个简单的操作,其中我显示PI的值为用户声明的十进制长度。例如,如果用户输入2,PI将打印出3.14。但是,我不断收到ArgumentsOutOfBounds错误。任何人都可以向我解释我做错了什么?设置PI小数位给用户在C#中的位置给定数量

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

哪条线是给你的例外,到底是什么? – Pac0

+4

调用'Console.ReadLine'和'int.TryParse'而不是将字符代码转换为'int'。 –

+0

@ Pac0对不起,这是一个'double piToPlaces = Math.Round(Math.PI,places);' – Robert

回答

2

两件事。

第一:下面一行在逻辑上不正确。通过读取返回的输出是一个charint变量

int decimalPlaces = (int)Console.Read(); 

你需要的是

int decimalPlaces = int.Parse(Console.ReadLine()); 

二:你的功能应该真正使用decimal而不是double当你想要做定点精确,因为double是浮点精度值

public static decimal Round(int places){ 
    decimal piToPlaces = Math.Round((decimal)Math.PI, places); 
    return piToPlaces; 
} 

这个应该解决您的异常,并且还避免任何潜在的浮点精度问题

0

当你使用Console.Read()直接读,你读输入的ASCII值到decimalPlaces

因此,如果您输入了2,则decimalPlaces的值将是50

你需要做的是使用Console.ReadLine()并对输入做int.TryParse(),然后将它传递给你的Round()方法。

string strNum = Console.ReadLine(); 
int decimalPlaces; 
int.TryParse(strNum, out decimalPlaces); 
Console.WriteLine(Round(decimalPlaces)); 
+0

对不起,我的回复中有一个错误,所以编辑它。 – Sach

0

请修改您从控制台阅读价值线,

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