如何在 C# 中将输入读取为整数?

来源:这里教程网 时间:2026-02-21 16:21:31 作者:

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

相关推荐