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助手提供,问题来源于学员提问