如何编写一个对4位数字的数字求和的程序? [英] How to write a program which sums the digits of a 4-digit number?

查看:481
本文介绍了如何编写一个对4位数字的数字求和的程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。如何编写一个对4位数字的数字求和的程序?我有一个有效的程序,但你必须分别输入数字。任何人都可以帮助或解释我做错了什么吗?我的教授告诉我们使用模数符号(%),但我不知道如何在这里使用它。到目前为止,我的代码如下:

Hi. How do I write a program that sums the digits of a 4-digit number? I have a program that works, but you have to input the digits separately. Can anyone help or possibly explain what I''m doing wrong? My professor told us as a hint to use the modulus sign (%), but i don''t know how I would use that here. My code so far is below:

展开 | 选择 | Wrap | 行号

推荐答案

你知道什么是modulous运营商呢?如何帮助您隔离四位数的数字?


顺便说一下,这不是您需要的唯一操作符,您还需要一个或多个普通算术运算符。
Do you know what the modulous operator does? How would it help you isolate the digits in a four digit number?

By the way that is not the only operator you will need you will need 1 or more of the normal arithmetic operators too.

您将遇到的一个问题是您正在读取整数,这将读取整个4位数字,而不仅仅是每个字符。如果你想按照自己的方式去做,你必须逐个字符地阅读它,并从每个数字中减去0以获得数值。


不幸的是,这是一种更不稳定的方法,因为默认情况下不会处理前面的负号或空格。


奇怪的是,有一个 Java论坛中的类似帖子,这可能对逻辑有所帮助。
One of the problems you will have is that you are reading in ints, which will read in the whole 4 digit number, not just each character. If you want to do it the way you are, you''d have to read it character by character, and subtract ''0'' from each digit to get the numeric value.

Unfortunately, this is a more precarious method, as a negative sign or a space in front will not be handled by default.

Oddly enough there was a similar post in the Java forum, which might help in terms of logic.


我不会为你做这件事,但基本知识是:


得到每个数字的mod 10并将它们加在一起。


欢呼,
I won''t do it for you but the basics are:

get the mod 10 of each digit and add each together.

cheers,


这篇关于如何编写一个对4位数字的数字求和的程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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