簡體   English   中英

嘗試將字符串轉換為int(C#)

[英]Attempting to convert a string to an int (C#)

我正在嘗試學習C#編碼(或與此有關的任何代碼)的基礎知識。 我不明白如何接受用戶輸入並將其放入一個字符串,以后可以用作整數。 我以為我可以這樣寫

string baseOfTriange = int.Parse(Console.ReadLine));

但它不起作用。 我也嘗試過浮動思考,也許就是這樣,但是,我只是迷失了這個概念。 到目前為止,這就是我所擁有的,只是我不知道如何將字符串轉換為int。 謝謝你的幫助。

static void Main(string[] args)
{
    // area of a triangle = base(height)/2

    Console.WriteLine("Welcome, enter your triangle dimensions. ");
    Console.WriteLine();

    Console.Write("What is the base of the triangle? ");
    string baseOfTriangle = int.Parse(Console.ReadLine());
    Console.WriteLine("You answered, " + baseOfTriangle + ". ");

    Console.Write("What is your height of the triangle? ");
    string heightOfTriangle = int.Parse(Console.ReadLine());
    Console.WriteLine("You answered, " + heightOfTriangle + ". ");

    Console.WriteLine("The area of the triangle is " + (baseOfTriangle * heightOfTriangle / 2));
    Console.ReadLine();
}

我假設您由於以下原因而遇到了編譯時錯誤:

string baseOfTriangle = int.Parse(Console.ReadLine());

int.Parse的返回類型是int但是您試圖將其分配給string類型的變量。 baseOfTriangleheightOfTriangle的類型更改為int解決您的問題。

int baseOfTriangle = int.Parse(Console.ReadLine());
^^^

另外,您可能需要浮點答案。 否則1*1/2將為您提供0的答案。將其更改為baseOfTriangle * heightOfTriangle / 2.0 或者更好地使用doubledouble.Parse

看看C#編程指南:如何:將字符串轉換為數字: http : //msdn.microsoft.com/zh-cn/library/bb397679.aspx

還要查看大多數c#內置數字類型的TryParse方法。 例如,int32.TryParse(): http : //msdn.microsoft.com/zh-cn/library/system.int32.tryparse (v=vs.110) .aspx

static void Main(string[] args)
{
    Console.Write("What is the base of the triangle? ");
    int baseOfTriangle = int.Parse(Console.ReadLine());

    Console.Write("What is your height of the triangle? ");
    int heightOfTriangle = int.Parse(Console.ReadLine());

    Console.WriteLine("The area of the triangle is {0}", (baseOfTriangle * heightOfTriangle) / 2);
    Console.ReadLine();
}

轉換為int的常用方法是使用Convert.ToInt32()

暫無
暫無

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

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