2009-05-26 115 views
1

我正在做一本书中的例子:Herbert Schildt的完整参考C#3.0。这是关于使用参数在Console.WriteLine中写入的。这里是例子: 我试过,但我得到了一个错误:参数错误c#

Project1.exe has encountered a problem and needs to be close. We are sorry for the inconvenience. Please tell Microsoft about this problem. Send Error Report or Don't Send. And if I click, I get another error in the command prompt. "Unhandled Exception: System.Format.Exception input string was not in a correct format. 
at System.Text.StringBuilder.AppendFormatError() 
at System.Text.StringBuilder.AppendFormat(IFormatProvider provider,String Format, Object[]args) 
at System.IO.TextWriter.WriteLine(String format, Object arg0) 
at System.IO.TextWriter.SyncTextWriter.WriteLine(String format, Object arg0) 
At Example2.Main() in D:\myPath

我不知道,如果这本书有一些错误,或者是我的代码? 我将不胜感激您的帮助。由于

One of the easiest ways to specify a format is to describe a template that WriteLine() will use. To do this, show an example of the format that you want, using #s to mark the digit positions. You can also specify the decimal point and commas. For example, here is a better way to display 10 divided by 3:
Console.WriteLine("Here is 10/3: {0:#.##}", 10.0/3.0);
The output from this statement is shown here: Here is 10/3: 3.33

顺便说一句,这是我的代码如下所示:

static void Main() 
    { 
    Console.WriteLine("Here is 10/3: {0:#.##)", 10); 
    } 

回答

9

您正在使用的格式参数错误的结局梅开二度。

请注意末尾括号)在#。##之后,它应该是一个}而不是(花括号)。

另外请注意,你已经离开了分工,如果你简单地改变你的代码,这(修正后的括号以及):

static void Main() 
{ 
    Console.WriteLine("Here is 10/3: {0:#.##}", 10/3); 
} 

然后你将有一个问题为好,因为那结果将是:

Here is 10/3: 3.00 

这样做的原因是,10月3日是整数除法,看看有多少次,每次3完全上升10个,这是3倍。

如果你想要浮点除法,除以3得到3和1/3,那么你需要确保至少有一个数字是浮点数,因此10.0/3会做。

+0

嗨Lasse V. Karlsen,谢谢我现在明白了。是的,它是大括号。这很简单。谢谢 – tintincutes 2009-05-26 20:15:54

-1

那是因为你的代码是不正确。

超过1个地方!

(支架和缺少“/3.0”部分)

2

更改)} - 只是一个错字,似乎。

+0

谢谢Noldorin,我明白了。我现在改变它;-) – tintincutes 2009-05-26 20:16:18

2

您的格式字符串错误。你有一个{配对)

+0

谢谢布赖恩;-)现在我明白了。 – tintincutes 2009-05-26 20:16:35

3

您的代码是错误的。您在字符串文字中使用括号而不是大括号。试试这个:

static void Main() 
    { 
     Console.WriteLine("Here is 10/3: {0:#.##}", 10); 
    } 
+0

感谢Adam,我明白了。感谢您的建议 – tintincutes 2009-05-26 20:17:18

1

它应该是:

Console.WriteLine("Here is 10/3: {0:#.##}", 10); 

当您正在使用的格式,你应该把它放在{和}

+0

感谢披头士我现在明白了。谢谢您的帮助。 – tintincutes 2009-05-26 20:17:32

+0

不客气! – Beatles1692 2009-05-26 20:51:45

1
下面

更正代码:

static void Main()  
{  
Console.WriteLine("Here is 10/3: {0:#.##}", 10.0/3);  
} 
+0

感谢patjbs我明白了:-)感谢您的帮助 – tintincutes 2009-05-26 20:18:24

1

在你的弦的结尾你有a)而不是a}

+0

嗨Fredrik感谢我的帮助。 – tintincutes 2009-05-26 20:18:52

0

让我也无条件地向其他人发布相同的答案!

用代码中的##}替换##)。