目的C-如何在数量增加数字? [英] Objective C- How to add digits in a number?

查看:114
本文介绍了目的C-如何在数量增加数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在一个特定的号码增加的数字,例如,如果数量为3234的结果应该是3 + 2 + 3 + 4 = 12

How do I add the digits in a particular number for example if the number is 3234 the result should be 3+2+3+4 = 12?

推荐答案

沿此线的东西应该这样做:

Something along the lines of this should do it:

int val = 3234;

int sum = 0;
while (val != 0) {
    sum += (val % 10);
    val = val / 10;
}

// Now use sum.

有关持续增加,直到你得到一个数字:

For continued adding until you get a single digit:

int val = 3234;

int sum = val;
while (sum > 9) {
    val = sum;
    sum = 0;
    while (val != 0) {
        sum += (val % 10);
        val = val / 10;
    }
}

// Now use sum.

请注意,这两种会破坏原来的 VAL 值。如果你想preserve它,你应该做一个副本或做这一个功能,所以原来保持不变。

Note that both of these are destructive to the original val value. If you want to preserve it, you should make a copy or do this in a function so the original is kept.

这篇关于目的C-如何在数量增加数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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