ZBLOG

Function to calculate the sum of digits of a number

You can calculate the sum of the digits of a number in various programming languages. Below are examples in Python, Java, and C++.

Python

def sum_of_digits(n):
    return sum(int(digit) for digit in str(n))

# Example usage
number = 12345
result = sum_of_digits(number)
print("Sum of digits:", result)

Java

public class Main {
    public static int sumOfDigits(int n) {
        int sum = 0;
        while (n != 0) {
            sum += n % 10; // Add last digit to sum
            n /= 10;       // Remove last digit from n
        }
        return sum;
    }

    public static void main(String[] args) {
        int number = 12345;
        int result = sumOfDigits(number);
        System.out.println("Sum of digits: " + result);
    }
}

C++

#include <iostream>
using namespace std;

int sumOfDigits(int n) {
    int sum = 0;
    while (n != 0) {
        sum += n % 10; // Add last digit to sum
        n /= 10;       // Remove last digit from n
    }
    return sum;
}

int main() {
    int number = 12345;
    int result = sumOfDigits(number);
    cout << "Sum of digits: " << result << endl;
    return 0;
}

In each example, the function calculates the sum of the digits by iterating through each digit of the number until there are no more digits left. You can test these functions with different numbers as needed!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=21378

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?