要在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
以上就是如何在 C# 中将输入读取为整数?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。