使用 While 循环和示例编写一个 C++ 程序来查找数字中各位数字之和。在 while 循环中,它将数字分解为单个数字,然后找到它们的总和。
在这里,我们使用 cout 语句在每次迭代时向您显示余数和总和的值,这有助于您理解执行过程。
#include<iostream>
using namespace std;
int main()
{
int number, reminder, digitSum = 0;
cout << "Please Enter the Number to calculate Sum of Digits = ";
cin >> number;
while (number > 0)
{
reminder = number % 10;
digitSum += reminder;
number = number / 10;
cout << "\nDigit = " << reminder << " and the Digit Sum = " << digitSum;
}
cout << "\n\nThe Sum of all Digits in a given Number = " << digitSum;
return 0;
}

C++ 程序使用 For 循环查找数字中各位数字之和
#include<iostream>
using namespace std;
int main()
{
int number, reminder, digitSum;
cout << "Please Enter the Number to calculate Sum of Digits = ";
cin >> number;
for(digitSum = 0; number > 0; number = number / 10)
{
reminder = number % 10;
digitSum += reminder;
cout << "\nDigit = " << reminder << " and the Digit Sum = " << digitSum;
}
cout << "\nThe Sum of all Digits in a given Number = " << digitSum;
return 0;
}
Please Enter the Number to calculate Sum of Digits = 785469
Digit = 9 and the Digit Sum = 9
Digit = 6 and the Digit Sum = 15
Digit = 4 and the Digit Sum = 19
Digit = 5 and the Digit Sum = 24
Digit = 8 and the Digit Sum = 32
Digit = 7 and the Digit Sum = 39
The Sum of all Digits in a given Number = 39
使用函数查找数字中各位数字之和的程序
在此 C++ 示例中,我们使用函数分离了逻辑。
#include<iostream>
using namespace std;
int sumOfDigits(int number)
{
int reminder, digitSum;
for(digitSum = 0; number > 0; number = number / 10)
{
reminder = number % 10;
digitSum += reminder;
cout << "\nDigit = " << reminder << " and the Digit Sum = " << digitSum;
}
return digitSum;
}
int main()
{
int num, digiSum;
cout << "Please Enter the Number to calculate Sum of Digits = ";
cin >> num;
digiSum = sumOfDigits(num);
cout << "\nThe Sum of all Digits in a given Number = " << digiSum;
return 0;
}
Please Enter the Number to calculate Sum of Digits = 78932
Digit = 2 and the Digit Sum = 2
Digit = 3 and the Digit Sum = 5
Digit = 9 and the Digit Sum = 14
Digit = 8 and the Digit Sum = 22
Digit = 7 and the Digit Sum = 29
The Sum of all Digits in a given Number = 29
下面的程序将使用递归查找数字中各位数字之和。
#include<iostream>
using namespace std;
int sumOfDigits(int number)
{
static int reminder, digitSum = 0;
if(number > 0)
{
reminder = number % 10;
digitSum += reminder;
sumOfDigits(number / 10);
return digitSum;
}
else
return 0;
}
int main()
{
int num, digiSum;
cout << "Please Enter the Number to calculate Sum of Digits = ";
cin >> num;
digiSum = sumOfDigits(num);
cout << "\nThe Sum of all Digits in a given Number = " << digiSum;
return 0;
}
Please Enter the Number to calculate Sum of Digits = 248769
The Sum of all Digits in a given Number = 36