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

csharpprogrammingserver side programming更新于 2025/7/12 10:37:17

要在 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("用户输入:");
      val = Console.ReadLine();

      // 转换为整数
      res = Convert.ToInt32(val);

      // 显示该行
      Console.WriteLine("Input = {0}", res);
   }
}

输出

用户输入:
Input = 0

以下是输出。输入由用户输入。

用户输入: 2
Input = 2

相关文章