C++ Experiment 1 7-4 Find the number of digits of an integer and the sum of the digits

7-4 Find the number of digits and the sum of the digits of the integer (15 points)
For a given positive integer N, find the number of digits and the sum of the digits.

Input format:

Input gives a positive integer N up to 10
​9​​ in one line.

Output format:

Print the number of digits of N and the sum of its digits in one line, separated by a space.

Input sample:

321
output sample:

3 6

code show as below:

#include <iostream>
using namespace std;

int main()
{
    
    
	int n, num = 0, tot = 0;
	cin>>n;
	while(n)	//此方法拆分数字非常简便
	{
    
    
		tot += n%10;
		num++;
		n /= 10;
	}
	cout<<num<<" "<<tot<<endl;
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325643317&siteId=291194637