2014-09-03 92 views
1

我正在做作業,但是在做作業時出現了一些問題。我將一個字符串值解析爲Int32,然後將它連接到一個字符串。任務是獲得用戶的年齡,並在10年內給他與他的年齡。字符串在與字符串連接時不會解析爲Int32

但是,當我嘗試將var age添加到字符串時,它不保留爲int,而是保留爲字符串。在這裏:Console.WriteLine(「你的年齡在10年將是:」+年齡+ 10);這種輸出2210,而不是32

如果我只打印了var年齡+ 10則輸出32

爲什麼會出現這樣的結果?

using System; 

namespace _07App 
{ 
class Program 
{ 
    static void Main() 
    { 
     Console.WriteLine("What is your age"); 
     var age = Int32.Parse(Console.ReadLine()); 
     Console.WriteLine("Your age in 10 years will be: "+ age + 10); 
     Console.WriteLine(age + 10); 
    } 
    } 
} 
+0

當您在字符串後面使用'+'時,c#會假定您正在合併某些字符串。所以它只是這樣做:''你的年齡在10年將是:FirstName10「' – 2014-09-03 06:46:57

+2

正在修復你的命名約定; 「姓氏」對於某個人來說是一個可怕的名字。 – 2014-09-03 06:48:32

+0

將變量'FirstName'的名稱更改爲'age'可能是明智的 – 2014-09-03 06:48:57

回答

3

這看起來是一個運算符優先級的問題,因爲你的名字被添加到字符串之前,它被添加到10

Console.WriteLine("Your age in 10 years will be: " +(FirstName + 10)); 
1

使用()當你在與串聯加INT值字符串

Console.WriteLine("Your age in 10 years will be: "+ (FirstName + 10)); 
1

更改爲:

Console.WriteLine("Your age in 10 years will be: "+ (age+ 10)); 

因爲Console.WriteLine("Your age in 10 years will be: "+ age + 10);將自動轉換爲字符串=「10」+「10」=「1010」