为什么我们使用“Convert.ToInt32(Console.ReadLine());”? [英] Why do we use "Convert.ToInt32(Console.ReadLine());"?

查看:256
本文介绍了为什么我们使用“Convert.ToInt32(Console.ReadLine());”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我在C#中遇到的众多程序中的一个。我想知道为什么我们使用Convert.ToInt32(Console.ReadLine()); ?



  / *   
* C#程序检查输入年份是否为闰年或不是
* /

使用系统;
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Text;

命名空间计划
{
class leapyear
{
静态 void Main( string [] args)
{
leapyear obj = new leapyear();
obj.readdata();
obj.leap();
}
int y;
public void readdata()
{
Console.WriteLine( 以四位数输入年份:);
y = Convert.ToInt32(Console.ReadLine());
}
public void leap()
{
if ((y% 4 == 0 && y% 100 != 0 )||(y% 400 == 0 ))
{
Console.WriteLine( {0}是闰年,y);
}
else
{
Console.WriteLine( {0}不是闰年,y);
}
Console.ReadLine();
}
}
}

解决方案

Console.ReadLine Method(System) [ ^ ]返回字符串值, y int type, Convert.ToInt32 Method(System) [ ^ ]将此字符串输入转换为int值。尝试阅读文档并理解


Console.ReadLine等待用户按下[ENTER]并返回之前输入的文本。 Convert.ToInt32将文本转换为数字,因此传入Console.ReadLine会将人输入1970的年份转换为1970年。


 Console.ReadLine()

返回字符串值,但是你不能对字符串变量执行任何算术运算,所以要从字符串转换为整数,我们使用

 Convert.ToInt32(StringValue) ; 


The following is one out of many programs i came across in C#. I want to know why we use "Convert.ToInt32(Console.ReadLine());" ?

/*
 * C# Program to Check Whether the Entered Year is a Leap Year or Not
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Program
{
    class leapyear
    {
        static void Main(string[] args)
        {
            leapyear obj = new leapyear();
            obj.readdata();
            obj.leap();
        }
        int y;
        public void readdata()
        {
            Console.WriteLine("Enter the Year in Four Digits : ");
            y = Convert.ToInt32(Console.ReadLine());
        }
        public void leap()
        {
            if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0))
            {
                Console.WriteLine("{0} is a Leap Year", y);
            }
            else
            {
                Console.WriteLine("{0} is not a Leap Year", y);
            }
            Console.ReadLine();
        }
    }
}

解决方案

Console.ReadLine Method (System)[^] return string value, y is int type, Convert.ToInt32 Method (System)[^] convert this string input to a int value. try to read the documentation and understand


Console.ReadLine waits until the user has pressed [ENTER] and returns the text the entered before that. Convert.ToInt32 converts text to a number, so passing in Console.ReadLine will convert the year the person has entered "1970" into the number 1970.


Console.ReadLine()

returns string value but you can't perform any arithmetic operation on string variable so to convert from string to integer we use

Convert.ToInt32(StringValue);


这篇关于为什么我们使用“Convert.ToInt32(Console.ReadLine());”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆