2009-05-26 112 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

讓我也無條件地向其他人發佈相同的答案!

用代碼中的##}替換##)。