看别人的代码写的就没记录
习题6-2 使用函数求特殊a串数列和
int fn( int a, int n )
{
int u = a;
for(int i=1;i<n;i++)
{
u = u*10+a;
}
return u;
}
int SumA( int a, int n )
{
int sum = 0;
for(int j = 1;j<=n;j++)
{
sum = sum+fn(a,j);
}
return sum;
}
习题6-3 使用函数输出指定范围内的完数
int factorsum( int number )
{
if(number == 1) return 0;
int sum = 1;
int i =2;
while(i<number)
{
if(number%i==0) sum = sum+i;
i++;
}
return sum;
}
void PrintPN( int m, int n )
{
int count = 0;
for(int i = m;i<=n;i++)
{
if(factorsum(i)==i)
{
count++;
printf("%d = 1",i);
int j = 2;
while(j<i)
{
if(i%j==0)
{
printf(" + ");
printf("%d",j);
}
j++;
}
putchar('\n');
}
}
if(count == 0) printf("No perfect number");
}
习题6-4 使用函数输出指定范围内的Fibonacci数
int fib( int n )
{
int a,b,c;
a=b=c=1;
for(int i=3;i<=n;i++)
{
c = a+b;
a = b;
b = c;
}
return c;
}
void PrintFN( int m, int n )
{
int oc = 0;
int j = 1;
while(fib(j)<m) j++;
int q = 1;
while(fib(q)<=n) q++;
q=q-1;
for(int i=m;i<=n;i++)
{
for(int k=j;fib(k)<=i;k++)
{
if(fib(k)==i)
{
oc = 1;
printf("%d",i);
if(k<q) printf(" ");
}
}
}
if(oc==0) printf("No Fibonacci number");
}
习题6-5 使用函数验证哥德巴赫猜想
int prime( int p )
{
if(p == 1) return 0;
if(p == 2) return 1;
for(int i = 2;i<(sqrt(p)+1);i++)
{
if(p%i==0) return 0;
}
return 1;
}
void Goldbach( int n )
{
int i = n-3;
while(i>=3)
{
if(prime(i)==1)
{
int j = n-i;
if(prime(j) == 1)
{
printf("%d=%d+%d",n,j,i);
break;
}
}
i = i-2;
}
}
习题6-6 使用函数输出一个整数的逆序数
int reverse( int number )
{
int sum, n;
sum = n = 0;
int a = number;
while(a!=0)
{
n++;
a = a/10;
}
while(number!=0)
{
int b = number%10;
for(int i=1;i<n;i++)
{
b = b*10;
}
sum = sum+b;
number = number/10;
n--;
}
return sum;
}
习题6-7 简单计算器
#include
int main()
{
int n,m;
int fact = 1;
char ch;
scanf("%d",&n);
ch = getchar();
while(ch!='=')
{
scanf("%d",&m);
if(ch == '+')
{
n = n+m;
}else if(ch == '-')
{
n = n-m;
}else if(ch == '*')
{
n = n*m;
}else if(ch == '/')
{
if(m==0) fact = 0;
else n = n/m;
}else fact = 0;
ch = getchar();
}
if(fact == 0) printf("ERROR");
else printf("%d",n);
return 0;
}
习题6-8 单词首字母大写
#include
int main()
{
int i = 1;
char ch;
ch = getchar();
while(ch!='\n')
{
if(i == 1)
{
if(ch>='a'&&ch<='z') ch = ch-'a'+'A';
}
putchar(ch);
i++;
if(ch == ' ') i = 1;
ch = getchar();
}
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)