C语言程序100例之C#版-029
C程序源代码:
【程序29】
题目:给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。
1. 程序分析:学会分解出每一位数,如下解释:(这里是一种简单的算法,师专数002班赵鑫提供)
2.程序源代码:
#include "stdio.h"
#include "conio.h"
main( )
{
long a,b,c,d,e,x;
scanf("%ld",&x);
a=x/10000;/*分解出万位*/
b=x%10000/1000;/*分解出千位*/
c=x%1000/100;/*分解出百位*/
d=x%100/10;/*分解出十位*/
e=x%10;/*分解出个位*/
if (a!=0) printf("there are 5, %ld %ld %ld %ld %ld\n",e,d,c,b,a);
else if (b!=0) printf("there are 4, %ld %ld %ld %ld\n",e,d,c,b);
else if (c!=0) printf(" there are 3,%ld %ld %ld\n",e,d,c);
else if (d!=0) printf("there are 2, %ld %ld\n",e,d);
else if (e!=0) printf(" there are 1,%ld\n",e);
getch();
}
########################
C#语言程序:
using System;
class C329
{
static void Main()
{
long a,b,c,d,e,x;
x=Convert.ToInt64(Console.ReadLine());
a=x/10000;
b=x%10000/1000;
c=x%1000/100;
d=x%100/10;
e=x%10;
if (a!=0) Console.Write("there are 5, {0} {1} {2} {3} {4}\n",e,d,c,b,a);
else if (b!=0) Console.Write("there are 4, {0} {1} {2} {3}\n",(int)e,(int)d,(int)c,(int)b);
else if (c!=0) Console.Write(" there are 3,{0} {1} {2}\n",(int)e,(int)d,(int)c);
else if (d!=0) Console.Write("there are 2, {0} {1}\n",(int)e,(int)d);
else if (e!=0) Console.Write(" there are 1,{0}\n",(int)e);
}
}
扩展1:平时写应用是,如果纯粹为了实现目标进行分解和倒序,可以考虑用字符串来处理,方便,快捷。但处理过程不是以数值计算的方式来实现的。
using System;
class C329_1
{
static void Main()
{
long x;
x=Convert.ToInt64(Console.ReadLine());
String y = x.ToString();
Console.Write("there are" + x.ToString().Length+",");
for (int i = 1; i <= y.Length; i++)
{
Console.Write(y.Substring(y.Length - i, 1));
Console.Write(" ");
}
}
}
扩展2:保持数值计算,(原题目要求为不多余5位的正整数)并且扩展输入数据长度(但不能超过所使用的数值类型的最大长度);
using System;
using System.Collections.Generic;
class C329_2
{
static void Main()
{
long x;
x=Convert.ToInt64(Console.ReadLine());
String y = x.ToString();
int z = x.ToString().Length;
Console.Write("there are " + z+",");
int a = 10;
int b = 0;
int c = (int)x;
List<int> d = new List<int>();
for (int i = y.Length-1; i >= 0; i--)
{
b = (int)Math.Pow(a, i);
d.Add(c / b);
c = (int)x % b;
}
d.Reverse();
for (int i = 0; i < d.Count;i++ )
{
Console.Write(d[i]);
Console.Write(" ");
}
}
}