View Code
1 #include<iostream> 2 using namespace std; 3 4 int f(int n) 5 { 6 int sum = 0; 7 while(n) 8 { 9 sum += n%10; 10 if(sum > 9) 11 sum = sum %10 + sum/10; 12 n /= 10; 13 } 14 return sum; 15 } 16 int main() 17 { 18 int n; 19 while(cin >> n, n != 0) 20 { 21 cout << f(n) << endl; 22 } 23 return 0; 24 }
应该是数位开的太小,导致死循环了,改进如下:
View Code
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 5 int f(string s) 6 { 7 int sum = 0; 8 for(int i = 0; i < s.size(); ++i) 9 { 10 sum += s[i] - '0'; 11 if(sum > 9) 12 sum = sum %10 + sum/10; 13 } 14 return sum; 15 } 16 int main() 17 { 18 string s; 19 while(cin >> s, s != "0") 20 { 21 cout << f(s) << endl; 22 } 23 return 0; 24 }