求一个自然数n的各位数字之和(n是小于1000的自然数)

#include <stdio.h>
#include"conio.h"
long fun(long n)

#include <iostream>
using namespace std;

int main() {
    int n, sum = 0;
    cout << "请输入一个小于1000的自然数: ";
    cin >> n;
    if (n < 0 || n >= 1000) {
        cout << "输入不合法" << endl;
        return 0;
    }
    while (n > 0) { // 取各位数字并求和
        sum += n % 10;
        n /= 10;
    }
    cout << "各位数字之和为:" << sum << endl;
    return 0;
}

如果以上回答对您有所帮助,点击一下采纳该答案~谢谢


#include <stdio.h>

long fun(long n) {
    long sum = 0;

    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }

    return num;
}