C语言100个经典例题(四)

【程序16】求最大公约数和最小公倍数。

题目:输入两个正整数m和n,求其最大公约数和最小公倍数。
程序分析:利用辗除法。

程序源代码:

#include "stdio.h"
#include "conio.h"
main()
{
  int a,b,num1,num2,temp;
  printf("please input two numbers:\n");
  scanf("%d,%d",&num1,&num2);
  if(num1<num2)/*交换两个数,使大数放在num1上*/
  {
    temp=num1;
    num1=num2;
    num2=temp;
  }
  a=num1;b=num2;
  while(b!=0)/*利用辗除法,直到b为0为止*/
  {
    temp=a%b;
    a=b;
    b=temp;
  }
  printf("gongyueshu:%d\n",a);
  printf("gongbeishu:%d\n",num1*num2/a);
  getch();
}

【程序17】输入一行字符,分别统计出其中英文字母、、、、的个数。

题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
程序分析:利用while语句,条件为输入的字符不为'\n'.
程序源代码:

#include "stdio.h"
#include "conio.h"
main()
{
  char c;
  int letters=0,space=0,digit=0,others=0;
  printf("please input some characters\n");
  while((c=getchar())!='\n')
  {
    if(c>='a'&&c<='z'||c>='A'&&c<='Z')
      letters++;
      else if(c==' ')
        space++;
        else if(c>='0'&&c<='9')
          digit++;
        else
          others++;
  }
  printf("all in all:char=%d space=%d digit=%d others=%d\n",letters,
  space,digit,others);
  getch();
}

【程序18】求s=a+aa+aaa+aaaa+aa...a的值

题目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时
共有5个数相加),几个数相加有键盘控制。
程序分析:关键是计算出每一项的值。

程序源代码:

#include "stdio.h"
#include "conio.h"
main()
{
  int a,n,count=1;
  long int sn=0,tn=0;
  printf("please input a and n\n");
  scanf("%d,%d",&a,&n);
  printf("a=%d,n=%d\n",a,n);
  while(count<=n)
  {
    tn=tn+a;
    sn=sn+tn;
    a=a*10;
    ++count;
  }
  printf("a+aa+...=%ld\n",sn);
  getch();
}

【程序19】完数。

题目:一个数如果恰好等于它的因子之和,这个数就称为“完数”。例如6=1+2+3.编程
找出1000以内的所有完数。

程序源代码:

#include "stdio.h"
#include "conio.h"
main()
{
  static int k[10];
  int i,j,n,s;
  for(j=2;j<1000;j++)
  {
    n=-1;
    s=j;
    for(i=1;i<j;i++)
    {
      if((j%i)==0)
      {
        n++;
        s=s-i;
        k[n]=i;
      }
    }
    if(s==0)
    {
      printf("%d is a wanshu",j);
      for(i=0;i<n;i++)
      printf("%d,",k);
      printf("%d\n",k[n]);
    }
  }
  getch();
}

【程序20】小球自由下落。

题目:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在
第10次落地时,共经过多少米?第10次反弹多高?

程序源代码:

#include "stdio.h"
#include "stdio.h"
main()
{
  float sn=100.0,hn=sn/2;
  int n;
  for(n=2;n<=10;n++)
  {
    sn=sn+2*hn;/*第n次落地时共经过的米数*/
    hn=hn/2; /*第n次反跳高度*/
  }
  printf("the total of road is %f\n",sn);
  printf("the tenth is %f meter\n",hn);
  getch();
}

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瑟瑟发抖的可乐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值