整数和字符串操作 [英] intergers and string manipulation

查看:71
本文介绍了整数和字符串操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
我正在开发一个c#应用程序,其中涉及加法,例如

1 + 2 + 3 + 4 =答案
当其中一个数字丢失时,应用程序无法汇总,而是引发异常.

如果缺少一些数字,我该如何继续添加,而我只添加可用的数字

万一所有数字都丢失了,我希望答案计算为一个像X这样的字符串char.
在此先感谢

Hi there
I am developing a c# application which involves adding up numbers eg

1+2+3+4=Answer
When one of the numbers is missing, application fails to sum up but instead it throws an exception.

How can i continue adding in case some numbers are missing, and i just add the available numbers

In case if all the numbers are missing, i want the answer to evaluate to a string char like X.
Thanks in advance

推荐答案

您应该将这些值加载到数组或列表或任何种类的集合中,并通过循环遍历来添加,这样实际的数量就可以了.变量无关紧要.要获得字符串格式的答案,只需在其上使用.ToString().
You should probably load those values into an array or list, or any sort of collection and add by looping through them, that way the actual number of variables is irrelevant. To get the answer in a string format just use .ToString() on it.


试一下...

Give this a shot...

string tmp = "1+2+3+5";
int total = tmp.Split('+').ToList().Sum(item => Convert.ToInt32(item));
Console.WriteLine(tmp + " = " + total.ToString());


很好的问题...哈哈哈.快给我们一些代码!听起来好像一定是一些琐碎的错误,误解或设计错误.
因此,让我们开始猜测:
我认为您是从一些控件(文本框?)中读取数字的,用户可以在其中输入数字.
您尝试将这些数字从文本框字符串转换为准备好进行计算".
如果其中一个文本框留为空白,则无法将其转换/解析为数字,这是引发异常的地方.

好猜测?
无论如何,请改善您的问题(显示代码).如果您总是谈论例外,请告诉我们哪个例外!
Very good question... Hahaha. Come on give us some code! Sounds like it must be some trivial bug, missunderstanding or desing mistake.
So let''s start guessing:
I think you read the numbers from some controls (textbox?) where the user can enter numbers.
You try to convert those numbers from the textbox strings to prepare them for your "calculation".
If one of the textboxes was left empty you can not convert/parse it to a number, this is where the exception is thrown.

Good guesses?
Anyway, please improve your question (show code). If you talk about exceptions allways tell us which one!


这篇关于整数和字符串操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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