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