如何在一行中输入5位数然后添加输入的所有数字? [英] How do I input 5 digits in a single line then add all the digits that are inputted?

查看:106
本文介绍了如何在一行中输入5位数然后添加输入的所有数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实施例。输入5位数:12345



1 + 2 + 3 + 4 + 5



请帮帮我我还是学生,想要从专家那里学到更多东西,谢谢:)

Ex. Enter 5 digits: 12345

1+2+3+4+5

please help me I'm still a students and wants to learn more from the experts, thanks :)

推荐答案

这有三个部分:

1 )阅读文本行 - 这是微不足道的,我假设你知道如何做到这一点。

2)将数字值加在一起

3)打印结果 - 再次这是微不足道的。



考虑中间位有点复杂,但这真的很简单:

1)设置一个总变量,并从零开始。

2)循环输入中的每个字符。

2.1)如果字符不是数字,则忽略它,或报告问题并停止。

2.2)否则,将其转换为整数值。这听起来很复杂,但事实并非如此:

There are three parts to this:
1) Read the line of text - this is trivial, and I assume you know how to do that.
2) Add the digit values together
3) Print the result - again this is trivial.

The middle bit is a little complicated to think about, but it's really pretty easy:
1) Set up a "total" variable, and start it at zero.
2) Loop through each character in the input.
2.1) If the character isn't a digit, ignore it, or report a problem and stop.
2.2) Otherwise, convert it to an integer value. This sounds complicated, but it isn't:
char c = '2';
int x = (int) (c - '0');

将值保留在变量 x

2.3)将新值添加到总额中

2.4)重复(2)中的下一个字符,直到用完字符为止。



循环非常简单:

Will leave the value two in the variable x
2.3) Add the new value into the total
2.4) Repeat for next character at (2) until you run out of characters.

And the loop is realy easy:

foreach (char c in myInputString)
   {
   ...
   }



所以试一试,看看你能走多远。现在你已经拥有了所有的东西,这很简单。


So give it a try, and see how far you get. It's pretty simple now you have all the pieces.


OriginalGriff的Solution1非常棒!



当你完成基础知识学习后,你仍然会对编程感兴趣,我建议阅读有关 Linq [ ^ ]。这是非常有趣的语言;)



Solution1 by OriginalGriff is excellent!

When you finish learning about basics, you'll be still interested of programming, i'd suggest to read about Linq[^]. It's very interesting language ;)

string s = "12345";
int sumOfDigits = s.Select(c=>Convert.ToInt32(c.ToString())).Sum();
Console.WriteLine("Sum of digits: '{0}' is {1}", s, sumOfDigits);
//or 
//as OriginalGriff suggested
sumOfDigits = s.Select(c=>Convert.ToInt32(c-'0')).Sum();
Console.WriteLine("Sum of digits: '{0}' is {1}", s, sumOfDigits);


这篇关于如何在一行中输入5位数然后添加输入的所有数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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