如何在 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

更新於: 22-10-2023

29K+ 瀏覽量

啟動您的事業

完成課程認證

開始
廣告
© . All rights reserved.