如何在 C# 中將輸入讀入為整數?


要將輸入作為整數讀入到 C# 中,請使用 Convert.ToInt32() 方法

res = Convert.ToInt32(val);

讓我們看看如何 −

Convert.ToInt32 方法將數字的指定字串表示轉換為等效的 32 位有符號整數。

首先,讀取控制檯輸入 −

string val;
val = Console.ReadLine();

讀取後,將其轉換為整數。

int res;
res = Convert.ToInt32(val);

讓我們看一個示例 −

示例

 即時演示

using System;
using System.Collections.Generic;

class Demo {
   static void Main() {
      string val;
      int res;
   
      Console.WriteLine("Input from user: ");
      val = Console.ReadLine();

      // convert to integer
      res = Convert.ToInt32(val);

      // display the line
      Console.WriteLine("Input = {0}", res);
   }
}

輸出

Input from user:
Input = 0

以下是輸出。輸入由使用者輸入。

Input from user: 2
Input = 2

更新於: 2023 年 10 月 22 日

29K+ 瀏覽量

開啟 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.