s2-1
设计项目s2-1,要求输出所有的 "水仙花数 ",所谓 "水仙花数 "是指一个三位数,其各位数字立方和等于该数本身。
/*
* 作者:JeronZhou
* 日期:2021-09-14
* 功能:输出所有的水仙花数
*/
using System;
namespace s2_1
{
class Program
{
public static void Main(string[] args)
{
int num;
int ge,shi,bai; //个位、十位、百位数字
Console.WriteLine("所有的水仙花数为:");
for(num=100; num<1000; num++)
{
bai = (num-(num%100))/100;
shi = ((num-100*bai)-((num-100*bai)%10))/10;
ge = num-100*bai-10*shi;
if(num == Math.Pow(ge, 3) + Math.Pow(shi, 3) + Math.Pow(bai, 3)) //判断是否为水仙花数
{
Console.Write(num);
Console.WriteLine();
}
}
Console.ReadLine();
}
}
}
运行程序,得到所有水仙花数为153、370、371、407,分析可知结果正确。
s2-2
设计项目s2-2,要求对于给定的下列字符串s,分别统计出其中英文字母、空格、数字和其它字符的个数。
string s = @“1.One day, a father and his little son were going home.
At this age, the boy was interested in all kinds of things and was
always asking questions. 2.Now, he asked, ‘What’s the meaning of the
word ‘Drunk’, dad?’ ‘Well, my son,’ his father replied, ‘look, there
are standing two policemen. 3.If I regard the two policemen as four
then I am drunk.’”;
/*
* 作者:JeronZhou
* 日期::2021-09-14
* 功能:统计字符串s中英文字母、空格、数字和其它字符的个数。
*/
using System;
namespace s2_2
{
class Program
{
public static void Main(string[] args)
{
string s = @"1.One day, a father and his little son were going home. At this age, the boy was interested in all kinds of things and was always asking questions. 2.Now, he asked, 'What's the meaning of the word 'Drunk', dad?' 'Well, my son,' his father replied, 'look, there are standing two policemen. 3.If I regard the two policemen as four then I am drunk.'";
int letter=0, space=0, num=0, other=0;
int i=s.Length-1;
while(i>=0) //遍历字符串中字符
{
if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z')) //统计字母数目
{
letter++;
}
else if(s[i]>='0' && s[i]<='9') //统计数字数目
{
num++;
}
else if(s[i]==' ' || s[i]=='\t') //统计空格数目
{
space++;
}
else //统计其他字符数目
{
other++;
}
i--;
}
Console.WriteLine("英文字母数目:" + letter);
Console.WriteLine("空 格数目:" + space);
Console.WriteLine("数 字数目:" + num);
Console.WriteLine("其他字符数目:" + other);
Console.ReadLine();
}
}
}
运行程序,得到英文字母数目为255,空格数目为62,数字数目为3,其他字符数目为26,分析可知结果正确。