3、输入a吧,b求最大公约数和最小公倍数
/*解题思路:先用辗转相除法求最大公约数,然后利用公式a*b/最大公约数=最小公倍数*/
#include<cstdio>
int main(){
int i,n,s,a,b,r,t;
printf("请输入a and b:\n");
scanf("%d,%d",&a,&b);
n = a*b;
if(a<b){
t = a;
a = b;
b = t;
}
//核心代码:用辗转相除法求最大公约数
r = a%b;
while(r){
a = b;
b = r;
r = a%b;
}
printf("最大公约数:%d\n",b);
//利用公式,求最小公倍数
s = n/b;
printf("最小公倍数:%d\n",s);
}
4、输入行字符,统计出其中的英文字母,数字,空格和其他字符的个数
#include<cstdio>
int main(){
char a;
int c = 0,
number = 0,
space = 0,
other = 0;
printf("请输入字符:\n");
while((a = getchar())&&a!='\n'){
if(a>='0'&&a<='9')
number++;
else if(a>='a'&&a<='z'||a>='A'&&a<='Z')
c++;
else if(a==' ')
space++;
else
other++;
}
printf("数字的个数%d\n字母的个数%d\n"
"空格的个数%d\n其他字符的个数%d\n",number,c,space,other);
}
5、输入n代表n位数,a代表数值,求和。a+aa+aaa+aaaa+aaaaa.
#include<cstdio>
int main(){
int n,a,i,t,sum;
sum = 0;
t = 0;
printf("请输入n and a\n");
scanf("%d,%d",&n,&a);
for(i=1;i<=n;i++){
t = t*10+a;
sum = sum+t;
}
printf("sum=%d",sum);
return 0;
}
6、求前20项的阶乘和
int fac(long long x);
#include<cstdio>
int main(){
int i;
long long sum=0,c = 0;
for(i=1;i<=20;i++){
c = fac(i);
printf("%d的阶乘为%lld\n",i,c);
sum = sum+c;
}
printf("前20项的阶乘为%lld\n",sum);
}
int fac(long long x){
long long y;
if(x==0)
y = 1;
else if(x>0)
y = fac(x-1)*x;
return (y);
}
8、输出所有的水仙花数
#include<cstdio>
int main(){
int a,b,c,i;
for(i=100;i<=999;i++){
a = i/100;
b = (i-a*100)/10;
c = i%10;
if(a*a*a+b*b*b+c*c*c==i)
printf("%d\n",i);
else
continue;
}
return 0;
}
9、求1000以内的完数,并按格式输出。
#include<cstdio>
int main(){
int i,j,m,s;
for(i=1;i<=1000;i++){
s = 0;
for(j=1;j<i;j++){
if(i%j==0)
s = s+j;
}
if(s==i){
printf("\n%d its factors",s);
for(m=1;m<s;m++){
if(s%m==0)
printf("%d ",m);
}
}
}
return 0;
}
10、求数列1/2+3/2+5/3+8/4+........前20项和
#include<cstdio>
int main(){
int i;
double sum,a,b,t;
sum = 0;
a = 1;
b = 2;
for(i=1;i<=20;i++){
sum = sum+a/b;
t = a;
a = a+b;
b = t;
}
printf("sum=%5.2lf",sum);
return 0;
}
11、