题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
程序分析:利用while语句,条件为输入的字符不为'\n'。
#include<stdio.h>
int main()
{
char c;
int letters=0,spaces=0,digits=0,others=0;
printf("请输入一些字母:\n");
while((c=getchar())!='\n')
{
if((c>='a'&&c<='z')||(c>='A'&&c<='Z'))
letters++;
else if(c>='0'&&c<='9')
digits++;
else if(c==' ')
spaces++;
else
others++;
}
printf("字母=%d,数字=%d,空格=%d,其他=%d\n",letters,digits,spaces,others);
return 0;
}
输出结果:
题目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加有键盘控制。
程序分析:关键是计算出每一项的值。
#include<stdio.h>
int main()
{
int s=0,a,n,t;
printf("请输入 a 和 n:\n");
scanf("%d%d",&a,&n);
t=a;
while(n>0)
{
s+=t;
a=a*10;
t+=a;
n--;
}
printf("a+aa+...=%d\n",s);
return 0;
}