Here’s a simple C function to calculate the sum of the digits of a number:
#include <stdio.h>
int sumOfDigits(int n) {
int sum = 0;
// Make sure to work with positive numbers
n = (n < 0) ? -n : n;
while (n != 0) {
sum += n % 10; // Add last digit to sum
n /= 10; // Remove last digit from n
}
return sum;
}
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
int result = sumOfDigits(number);
printf("Sum of digits: %d\n", result);
return 0;
}
Explanation:
- Function Definition:
sumOfDigits
takes an integern
as input and returns the sum of its digits. - Handling Negative Numbers: The function converts negative numbers to positive using the ternary operator, so it can handle both cases properly.
- While Loop: The loop continues until there are no more digits left in the number (
n
becomes0
). Inside the loop, it adds the last digit tosum
and removes that digit fromn
. - Main Function: It prompts the user for input, calls the
sumOfDigits
function, and prints the result.
You can compile this code using any C compiler and run it to see how it works!
内容由零声教学AI助手提供,问题来源于学员提问