如何在 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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP