C语言,循环结构

1、输入两个正整数,如12和8求其最大公约数(4)和最小公倍数(24)。
2、输入一行字符,分别统计其中中英文字母,空格,数字和其他字符的个数。

1.#include <stdio.h>

int main (void)
{
int m, n, p, tmp;

printf ("Please type in two number:\n");
scanf ("%i %i", &m, &n); //输入两个数,分别放入m, n
p=m*n; //先把两数的积算出来,后面m和n的值会有变

while (n!=0){
tmp=m%n;
m=n;
n=tmp; //这段是求最大公约数的算法
}

printf ("The GCD is %i\n", m); //上面的算法n=0时m这时的值就是最大公约数
printf ("The LCM is %i\n", p/m);//两数的积除以最大公约数就是最小公倍数了

return 0;
}
2.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
{
int i;
unsigned letters = 0;
unsigned spaces = 0;
unsigned digits = 0;
unsigned others = 0;
char line[256];
printf("Enter a line of words: \n");
gets(line);
for(i = 0; i < strlen(line); ++i)
{
if(isalpha(line[i]))
++letters;
else if(isspace(line[i]))
++spaces;
else if(isdigit(line[i]))
++digits;
else
++others;
}
printf("The line you entered has:\n");
printf("%d letters\n", letters);
printf("%d spaces\n", spaces);
printf("%d digits\n", digits);
printf("%d others\n", others);
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-05-12
最大公约数和最小公倍数
#include <stdio.h>
void main()
{
int a,b,num1,num2,temp;
while(1)
{
printf("请输入两个正整数(数字中间用空格隔开):\n");
scanf("%d%d",&num1,&num2);
if(num1<num2)
{
temp=num1;
num1=num2;
num2=temp;
}
a=num1;
b=num2;
while(b!=0)
{
temp=a%b;
a=b;
b=temp;
}
printf("最大公约数为:%d\n",a);
printf("最小公倍数为:%d\n\n",num1*num2/a);
}
}
/*输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。*/
#include <stdio.h>
void main()
{
char c;
int letter=0,space=0,digit=0,other=0;
printf("请输入一行字符\n");
while((c=getchar())!='\n')
{
if(c>='a'&&c<='z'||c>='A'&&c<='Z')
letter++;
else if(c==' ')
space++;
else if(c>='0'&&c<='9')
digit++;
else
other++;
}
printf("其中:字母数=%d 空格数=%d 数字数=%d 其它字符=%d\n",letter, space,digit,other);
}
好了,就这么多了,另外谭浩强版的C程序设计(第三版)的课后习题答案要的话可以发给你。
第2个回答  2010-05-12
这里给出大致编程的想法:
1。输入函数就不说了,在循环结构外利用输入函数输入了两个正整数,然后进入主循环,有两种结构,一种用While(1)函数,但是需要注意的是,在找出结果后需要用break函数跳出循环,否侧会形成死循环,另外一种是用for()循环语句,其中循环输入的两个数中最小的一个数的次数,我们要用到第二种循环结构,循环体内让两个数都分别对从1开始的数进行取余,当两个数取余后都为零则将该数存在一变量中,继续循环,每次出现同时为零的情况就把数覆盖之前的变量值,最后在被取余数等于两数中最大值时跳出循环。同样,最小公倍数是用两数中最大的值从1开始乘,然后对小的数取余,如果取余为零的话,那么这个乘积的数就为最小公倍数。
2。对照ASCII的表,里面的数字,英文字母,其他字符都在不同的数字域,利用一个循环程序逐个比较后,分别计数就能实现功能了,需要注意的是char型变量和int型变量的转换。
相似回答