简体   繁体   English

如何在C#中使用Convert.ToSingle()将字符串更改为int

[英]How to change a string to an int using Convert.ToSingle() in C#

I am making an age calculator, and am asking for the person birth month and year. 我正在制作年龄计算器,并要求该人出生的月份和年份。 They are to enter the month as a number, eg may would be 5. After that I am doing a System.Convert.ToSingle() on the string for their birth month. 他们将以数字形式输入月份,例如可能是5。之后,我在其出生月份的字符串上执行System.Convert.ToSingle() But It says I need a cast. 但是它说我需要演员。 I don't know how to format a cast on this and have researched it for about an hour. 我不知道如何格式化演员表,并且已经研究了大约一个小时。 Any help would be greatly appreciated: 任何帮助将不胜感激:

static void Age()
    {
        Console.WriteLine("What month were you born in?");
        string ageMonth = Console.ReadLine();
        Console.WriteLine("What year were you born in?");
        string ageYear = Console.ReadLine();

        DateTime currentMonth = DateTime.Now;

        int numberMonth;
        numberMonth = Convert.ToSingle(ageMonth);
    }

使用int.Parse

int.Parse(ageMonth)

int numberMonth = int.Parse(ageMonth);

请注意,如果ageMonth不包含有效的整数,这将引发异常。

You should probaly use 您应该正确使用

int.TryParse(ageMonth, out numberMonth)

Handle the boolean result to make sure that they actually input an int because other options would through an exception if the user did not input an int (returns true if it was converted and then numberMonth has the int that was parsed, false if the string could not be parsed). 处理布尔结果,以确保他们实际上输入的int,因为其他选项将通过一个异常,如果用户没有输入的int (返回true,如果它被转换,然后numberMonth有被解析的INT,假如果字符串可能无法解析)。 Never trust users to input the right type of information and you should protect your code. 永远不要相信用户输入正确的信息类型,您应该保护自己的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM