无法隐式转换string类型为int [英] Cannot implicitly convert type string to int

查看:291
本文介绍了无法隐式转换string类型为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  Console.WriteLine(请输入一些数字); 
INT总和= 0;
为(;;)
{
列输入=到Console.ReadLine();
如果(string.IsNullOrEmpty(输入))
{
中断;
}
INT inputParsed = int.Parse(input.ToString());
INT sumParsed = int.Parse(sum.ToString());
总和= SUM +输入; //抛出一个错误在这里

Console.WriteLine(总和);



我希望我的程序中,通过即使我已经分析显示用户输入的所有数字的总和所有的变量需要时,它抛出一个不能隐式转换类型'字符串'到'廉政'的错误。什么是错的。


解决方案

 总和= SUM +输入?; //此处将引发错误



应该是:



 总和=总和+ inputParsed; 

您使用的是原始输入,而不是解析值。而且你不需要 sumParsed ,因为你只是保持总金额在键,你这样做没有必要的投诠释为一个字符串,然后解析回一个整数。


    Console.WriteLine ("Please enter some numbers");
        int sum = 0;
        for(;;)
        {
            string input = Console.ReadLine ();
            if (string.IsNullOrEmpty (input))
            {
                break;
            }
            int inputParsed = int.Parse (input.ToString ());
            int sumParsed = int.Parse (sum.ToString ());
            sum = sum + input; // throws an error here

            Console.WriteLine (sum);

I want my programme to show the sum of all numbers entered by user, by even though I have parsed all the variables needed, it throws an "cannot implicitly convert type 'string' to 'int'" error. What's wrong?

解决方案

sum = sum + input; //throws an error here

should be:

sum = sum + inputParsed ;

You are using the original input instead of the parsed value. And you don't need sumParsed because you just keep the total sum in sum and you do no need to cast the int to a string and then parse it back to an integer.

这篇关于无法隐式转换string类型为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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