求一个比较有意思的编程算法

求一个比较有意思的编程算法,第1张

*问题分析与算法设计

根据题意可以将解题过程分为三步:

1)计算从1990年1月1日开始至指定日期共有多少天;

2)由于“打鱼”和“晒网”的周期为5天,所以将计算出的天数用5去除;

3)根据余数判断他是在“打鱼”还是在“晒网”;

若 余数为1,2,3,则他是在“打鱼”

否则 是在“晒网”

在这三步中,关键是第一步。求从1990年1月1日至指定日期有多少天,要判断经历年份中是否有闰年,二月为29天,平年为28天。闰年的方法可以用伪语句

描述如下:

如果 ((年能被4除尽 且 不能被100除尽)或 能被400除尽)

则 该年是闰年;

否则不是闰年。

C语言中判断能否整除可以使用求余运算(即求模)

*程序与程序注释

#include<stdio.h>

int days(struct date day)

struct date{

int year

int month

int day

}

void main()

{

struct date today,term

int yearday,year,day

printf("Enter year/month/day:")

scanf("%d%d%d",&today.year,&today.month,&today.day) /*输入日期*/

term.month=12 /*设置变量的初始值:月*/

term.day=31/*设置变量的初始值:日*/

for(yearday=0,year=1990year<today.yearyear++)

{

term.year=year

yearday+=days(term)/*计算从1990年至指定年的前一年共有多少天*/

}

yearday+=days(today) /*加上指定年中到指定日期的天数*/

day=yearday%5 /*求余数*/

if(day>0&&day<4) printf("he was fishing at that day.\n") /*打印结果*/

else printf("He was sleeping at that day.\n")

}

int days(struct date day)

{

static int day_tab[2][13]=

{{0,31,28,31,30,31,30,31,31,30,31,30,31,}, /*平均每月的天数*/

{0,31,29,31,30,31,30,31,31,30,31,30,31,},

}

int i,lp

lp=day.year%4==0&&day.year%100!=0||day.year%400==0

/*判定year为闰年还是平年,lp=0为平年,非0为闰年*/

for(i=1i<day.monthi++)/*计算本年中自1月1日起的天数*/

day.day+=day_tab[lp][i]

return day.day

}

*运行结果

Enter year/month/day:1991 10 25

He was fishing at day.

Enter year/month/day:1992 10 25

He was sleeping at day.

Enter year/month/day:1993 10 25

He was sleeping at day

function check($data , $n){

$last0 = 0

$first1 = 0

$last2 = 0

$first3 = 0

$num = $data

echo "\n\n"

for ($j=1 $j <= $n $j++) { 

# code...

$a = floor($num/pow(10, $n-$j))

if ($a>3) {

return 0

}elseif (0==$a) {

$last0 = $j

}elseif (1==$a) {

$first1 = (0==$first1) ? $j : $first1

}elseif (2==$a) {

$last2 = $j

}elseif (3==$a) {

$first3 = (0==$first3) ? $j : $first3

}

$num = $num%pow(10, $n-$j)

echo "$a $last0,$first1,$last2,$first3 $num \n"

}

if ($last0>$first1 || $last2 > $first3) {

return 0

}

if (0==$last0 || 0==$first1 || 0==$last2 || 0==$first3) {

return 0

}

return $data

}

function a($n){

$sum = 0

for ($i=pow(10, $n-1) $i < pow(10, $n)-1 $i++) { 

# code...

$result = check($i , $n)

if (0 != $result) {

# code...

$sum++

// echo $i

// echo "\t"

// echo $result

if (0 == $sum%10) {

echo "\n"

}

}

}

echo $sum%1000000007

}

PHP语言写的,没有C环境,就把变量名改改就能用


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/11355788.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-15
下一篇 2023-05-15

发表评论

登录后才能评论

评论列表(0条)

保存