所以(x+2y)<=100,且(x+5z)是偶数
对 z 作循环,求 x 的可能值如下:
z=0, x=100, 98, 96, ... 0
z=1, x=95, 93, ..., 1
z=2, x=90, 88, ..., 0
z=3, x=85, 83, ..., 1
z=4, x=80, 78, ..., 0
......
z=19, x=5, 3, 1
z=20, x=0
因此,组合总数为 100 以内的偶数+95 以内的奇数+90 以内的偶数+...+5 以内的奇数+1,
即
(51+48)+(46+43)+(41+38)+(36+33)+(31+28)+(26+23)+(21+18)+(16+13)+(11+8)+(6+3)+1
为
:
某个偶数 m 以内的偶数个数(包括 0)可以表示为 m/2+1=(m+2)/2
某个奇数 m 以内的奇数个数也可以表示为(m+2)/2
所以,求总的组合次数可以编程为:
number=0;
for (int m=0;m<=100;m+=5)
{
number+=(m+2)/2;
}
cout<
事——这不是一个专业的研发人员的行为。
那么,那种最容易想到的算法就完全没有用吗?不,这种算法正好可以用来验证新算法
的正确性,在调试阶段,这非常有用。在很多大公司,例如微软,都采用了这种方法:在调
试阶段,对一些重要的需要好的算法来实现的程序,而这种好的算法又比较复杂时,同时用
容易想到的算法来验证这段程序,如果两种算法得出的结果不一致(而最容易想到的算法保
证是正确的),那么说明优化的算法出了问题,需要修改。
可以举例表示为:
#ifdef DEBUG
int simple();
#end if
int optimize();
......
in a function:
{
result=optimize();
ASSERT(result==simple());
}
这样,在调试阶段,如果简单算法和优化算法的结果不一致,就会打出断言。同时,在程
序的发布版本,却不会包含笨重的 simple()函数。——任何大型工程软件都需要预先设计
良
好的调试手段,而这里提到的就是一种有用的方法。
一个学生的信息是:姓名,学号,性别,年龄等信息,用一个链表,把这些学生信息连在一
起, 给出一个 age, 在些链表中删除学生年龄等于 age 的学生信息。
#include "stdio.h"
#include "conio.h"
struct stu{
char name[20];
char sex;
int no;
int age;
struct stu * next;
}*linklist;
struct stu *creatlist(int n)
{
int i;
//h 为头结点,p 为前一结点,s 为当前结点
struct stu *h,*p,*s;
h = (struct stu *)malloc(sizeof(struct stu));
h->next = NULL;
p=h;
for(i=0;inext = s;
printf("Please input the information of the student: name sex no age \n");
scanf("%s %c %d %d",s->name,&s->sex,&s->no,&s->age);
s->next = NULL;
p = s;
}
printf("Create successful!");
return(h);
}
void deletelist(struct stu *s,int a)
{
struct stu *p;
while(s->age!=a)
{
p = s;
s = s->next;
}
if(s==NULL)
printf("The record is not exist.");
else
{
p->next = s->next;
printf("Delete successful!");
}
}
void display(struct stu *s)
{
s = s->next;
while(s!=NULL)
{
printf("%s %c %d %d\n",s->name,s->sex,s->no,s->age);
s = s->next;
}
}
int main()
{
struct stu *s;
int n,age;
printf("Please input the length of seqlist:\n");
scanf("%d",&n);
s = creatlist(n);
display(s);
printf("Please input the age:\n");
scanf("%d",&age);
deletelist(s,age);
display(s);
return 0;
}
2、实现一个函数,把一个字符串中的字符从小写转为大写。
#include "stdio.h"
#include "conio.h"
void uppers(char *s,char *us)
{
for(;*s!='\0';s++,us++)
{
if(*s>='a'&&*s<='z')
*us = *s-32;
else
*us = *s;
}
*us = '\0';
}
int main()
{
char *s,*us;
char ss[20];
printf("Please input a string:\n");
scanf("%s",ss);
s = ss;
uppers(s,us);
printf("The result is:\n%s\n",us);
getch();
}
随机输入一个数,判断它是不是对称数(回文数)(如 3,121,12321,45254)。不能用字
符串库函数
/***************************************************************
1.
函数名称:Symmetry
功能: 判断一个数时候为回文数(121,35653)
输入: 长整型的数
输出: 若为回文数返回值为 1 esle 0
******************************************************************/
unsigned char Symmetry (long n)
{
long i,temp;
i=n; temp=0;
while(i) //不用出现长度问题,将数按高低位掉换
{
temp=temp*10+i%10;
i/=10;
}
return(temp==n);
}
方法一
/* ---------------------------------------------------------------------------
功能:
判断字符串是否为回文数字
实现:
先将字符串转换为正整数,再将正整数逆序组合为新的正整数,两数相同则为回文数字
输入:
char *s:待判断的字符串