找到数字的总和,直到只剩下1位数 [英] Find the sum of the digits until only 1 digit remains
本文介绍了找到数字的总和,直到只剩下1位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我在创建一个循环达到1位数时遇到了一些困难。例如,999992确实变为47和11,但不是2,因为它应该....
这是我的代码:
Hi guys,
I am having some difficulties creating a loop to get to 1 digit. E.g 999992 does change to 47 and 11, but not to 2 as it should....
Here's my code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int n, sum=0, total=0;
cout << "Enter an integer." << endl;
cin >> n;
cout << "You have entered: " << n << endl;
while (n > 0) {
sum += n % 10;
n /= 10;
}
cout << "The digitsum is: " << sum << endl;
if (sum < 10)
cout << "The total digitsum is: "<< sum << endl;
else
do {
total += sum % 10;
sum /= 10;
cout << "The total digitsum is: " << total << endl;
} while (total < 10);
system("pause");
return 0;
}
任何人都可以帮我吗?
Can anyone help me out here?
推荐答案
请参阅我的评论功能。公平规则告诉使用:它足以找到第一个bug,然后你应该把它带入它帐户并修复它。
至少创建两个函数:一个计算数字之和,另一个代表外循环。您的查找数字总和的算法第一次正常工作。如果你把它作为一个单独的函数,变量sum
将在每次调用时初始化为0。问题的其余部分将以微不足道的方式解决。现在轮到你了。
-SA
Please see my comments to the function. Fair rules tell use: it's enough to locate just first bug, then you should take it into it account and fix it.
Create at least two more functions: one calculating sum of digits, another one representing outer cycle. Your algorithm of finding sum of digits works correctly for the very first time. If you make it a separate function, the variablesum
will be initialized to 0 on each call. The rest of the problem will be solved in a trivial way. It's your turn now.
—SA
这篇关于找到数字的总和,直到只剩下1位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文