输入一个正整数,将其各位数相加,一直加到只剩一位数为止。

输入一个正整数,将其各位数相加,一直加到只剩一位数为止。

#include
#include
#define N 10
#pragma warning(disable:4996)
int power(int m, int b)
{
	int sum1=1;
	for (int i = b; i >= 1; i--)
	{
		sum1*=m;
	}
	return sum1;
}
int main()
{
	int  a, a1, i, j, iflag = 0, n, sum, summ = 0, k = 0;
	printf("input 位数:\n");
	scanf("%d", &n);
	printf("input 数值:\n");
	scanf("%d", &a);
	summ = 0;
	sum = a;
	//a = power(10, 4);
	//printf("数=%d\n", a);
	//system("pause");
	while (1)
	{
		if (n >=1)
		{

			a1= power(10, (n - 1));
			summ += sum / a1;
			n--;
			sum= sum % power(10, n);
			//if (summ < 10)iflag = 2;

		}
		if (n == 0)
		{

			sum = summ;
			if (summ < 10)iflag = 2; 
			else { summ = 0; iflag = 1; }
			

		}
		if (iflag == 1)
		{
			while (1)
			{
				if (sum / (10 * (n + 1)) != 0)
					n++;
				else 
				{iflag = 0; n++; break; }
			}
		}
		if(iflag==2)
		{
			sum = summ; break;
		}

		
	}
	printf("%d\n", sum);
	system("pause");
}

你可能感兴趣的:(C语言)