簡體   English   中英

與字符串連接時,字符串不解析為Int32

[英]String doesn't parse to Int32 when concatenated with a string

我正在做作業,但是在做作業時出現了問題。 我正在將字符串值解析為Int32,然后將其連接為字符串。 任務是獲取用戶的年齡並在10年內給他年齡。

但是,當我嘗試將var age添加到字符串中時,它不會保留為int而是保留為字符串。 此處:Console.WriteLine(“您的10年年齡將是:” + age + 10); 這將輸出2210而不是32。

如果僅打印var age + 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);
    }
  }
}

這似乎是一個運算符優先級問題,因為將您的名字先添加到字符串中,然后再添加到字符串10中。

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

在與字符串連接時添加int值時使用()

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

改成:

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

因為Console.WriteLine("Your age in 10 years will be: "+ age + 10); 將年齡自動轉換為String =“ 10” +“ 10” =“ 1010”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM